babylon.scene.ts 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567
  1. module BABYLON {
  2. export interface IDisposable {
  3. dispose(): void;
  4. }
  5. /**
  6. * Represents a scene to be rendered by the engine.
  7. * @see http://doc.babylonjs.com/page.php?p=21911
  8. */
  9. export class Scene {
  10. // Statics
  11. private static _FOGMODE_NONE = 0;
  12. private static _FOGMODE_EXP = 1;
  13. private static _FOGMODE_EXP2 = 2;
  14. private static _FOGMODE_LINEAR = 3;
  15. public static MinDeltaTime = 1.0;
  16. public static MaxDeltaTime = 1000.0;
  17. public static get FOGMODE_NONE(): number {
  18. return Scene._FOGMODE_NONE;
  19. }
  20. public static get FOGMODE_EXP(): number {
  21. return Scene._FOGMODE_EXP;
  22. }
  23. public static get FOGMODE_EXP2(): number {
  24. return Scene._FOGMODE_EXP2;
  25. }
  26. public static get FOGMODE_LINEAR(): number {
  27. return Scene._FOGMODE_LINEAR;
  28. }
  29. // Members
  30. public autoClear = true;
  31. public clearColor: any = new Color3(0.2, 0.2, 0.3);
  32. public ambientColor = new Color3(0, 0, 0);
  33. /**
  34. * A function to be executed before rendering this scene
  35. * @type {Function}
  36. */
  37. public beforeRender: () => void;
  38. /**
  39. * A function to be executed after rendering this scene
  40. * @type {Function}
  41. */
  42. public afterRender: () => void;
  43. /**
  44. * A function to be executed when this scene is disposed.
  45. * @type {Function}
  46. */
  47. public onDispose: () => void;
  48. public beforeCameraRender: (camera: Camera) => void;
  49. public afterCameraRender: (camera: Camera) => void;
  50. public forceWireframe = false;
  51. public forcePointsCloud = false;
  52. public forceShowBoundingBoxes = false;
  53. public clipPlane: Plane;
  54. public animationsEnabled = true;
  55. public constantlyUpdateMeshUnderPointer = false;
  56. // Pointers
  57. private _onPointerMove: (evt: PointerEvent) => void;
  58. private _onPointerDown: (evt: PointerEvent) => void;
  59. private _onPointerUp: (evt: PointerEvent) => void;
  60. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  61. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  62. public onPointerUp: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  63. public onPointerDownUp: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  64. public cameraToUseForPointers: Camera = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  65. private _pointerX: number;
  66. private _pointerY: number;
  67. private _meshUnderPointer: AbstractMesh;
  68. private _startingPointerPosition = new Vector2(0, 0);
  69. private _startingPointerTime = 0;
  70. // Mirror
  71. public _mirroredCameraPosition: Vector3;
  72. // Keyboard
  73. private _onKeyDown: (evt: Event) => void;
  74. private _onKeyUp: (evt: Event) => void;
  75. // Fog
  76. /**
  77. * is fog enabled on this scene.
  78. * @type {boolean}
  79. */
  80. public fogEnabled = true;
  81. public fogMode = Scene.FOGMODE_NONE;
  82. public fogColor = new Color3(0.2, 0.2, 0.3);
  83. public fogDensity = 0.1;
  84. public fogStart = 0;
  85. public fogEnd = 1000.0;
  86. // Lights
  87. /**
  88. * is shadow enabled on this scene.
  89. * @type {boolean}
  90. */
  91. public shadowsEnabled = true;
  92. /**
  93. * is light enabled on this scene.
  94. * @type {boolean}
  95. */
  96. public lightsEnabled = true;
  97. /**
  98. * All of the lights added to this scene.
  99. * @see BABYLON.Light
  100. * @type {BABYLON.Light[]}
  101. */
  102. public lights = new Array<Light>();
  103. public onNewLightAdded: (newLight?: Light, positionInArray?: number, scene?: Scene) => void;
  104. public onLightRemoved: (removedLight?: Light) => void;
  105. // Cameras
  106. /**
  107. * All of the cameras added to this scene.
  108. * @see BABYLON.Camera
  109. * @type {BABYLON.Camera[]}
  110. */
  111. public cameras = new Array<Camera>();
  112. public onNewCameraAdded: (newCamera?: Camera, positionInArray?: number, scene?: Scene) => void;
  113. public onCameraRemoved: (removedCamera?: Camera) => void;
  114. public activeCameras = new Array<Camera>();
  115. public activeCamera: Camera;
  116. // Meshes
  117. /**
  118. * All of the (abstract) meshes added to this scene.
  119. * @see BABYLON.AbstractMesh
  120. * @type {BABYLON.AbstractMesh[]}
  121. */
  122. public meshes = new Array<AbstractMesh>();
  123. public onNewMeshAdded: (newMesh?: AbstractMesh, positionInArray?: number, scene?: Scene) => void;
  124. public onMeshRemoved: (removedMesh?: AbstractMesh) => void;
  125. // Geometries
  126. private _geometries = new Array<Geometry>();
  127. public onGeometryAdded: (newGeometry?: Geometry) => void;
  128. public onGeometryRemoved: (removedGeometry?: Geometry) => void;
  129. public materials = new Array<Material>();
  130. public multiMaterials = new Array<MultiMaterial>();
  131. public defaultMaterial = new StandardMaterial("default material", this);
  132. // Textures
  133. public texturesEnabled = true;
  134. public textures = new Array<BaseTexture>();
  135. // Particles
  136. public particlesEnabled = true;
  137. public particleSystems = new Array<ParticleSystem>();
  138. // Sprites
  139. public spritesEnabled = true;
  140. public spriteManagers = new Array<SpriteManager>();
  141. // Layers
  142. public layers = new Array<Layer>();
  143. // Skeletons
  144. public skeletonsEnabled = true;
  145. public skeletons = new Array<Skeleton>();
  146. // Lens flares
  147. public lensFlaresEnabled = true;
  148. public lensFlareSystems = new Array<LensFlareSystem>();
  149. // Collisions
  150. public collisionsEnabled = true;
  151. private _workerCollisions;
  152. public collisionCoordinator: ICollisionCoordinator;
  153. public gravity = new Vector3(0, -9.807, 0);
  154. // Postprocesses
  155. public postProcessesEnabled = true;
  156. public postProcessManager: PostProcessManager;
  157. public postProcessRenderPipelineManager: PostProcessRenderPipelineManager;
  158. // Customs render targets
  159. public renderTargetsEnabled = true;
  160. public dumpNextRenderTargets = false;
  161. public customRenderTargets = new Array<RenderTargetTexture>();
  162. // Delay loading
  163. public useDelayedTextureLoading: boolean;
  164. // Imported meshes
  165. public importedMeshesFiles = new Array<String>();
  166. // Probes
  167. public probesEnabled = true;
  168. public reflectionProbes = new Array<ReflectionProbe>();
  169. // Database
  170. public database; //ANY
  171. // Actions
  172. /**
  173. * This scene's action manager
  174. * @type {BABYLON.ActionManager}
  175. */
  176. public actionManager: ActionManager;
  177. public _actionManagers = new Array<ActionManager>();
  178. private _meshesForIntersections = new SmartArray<AbstractMesh>(256);
  179. // Procedural textures
  180. public proceduralTexturesEnabled = true;
  181. public _proceduralTextures = new Array<ProceduralTexture>();
  182. // Sound Tracks
  183. public mainSoundTrack: SoundTrack;
  184. public soundTracks = new Array<SoundTrack>();
  185. private _audioEnabled = true;
  186. private _headphone = false;
  187. //Simplification Queue
  188. public simplificationQueue: SimplificationQueue;
  189. // Private
  190. private _engine: Engine;
  191. private _totalVertices = 0;
  192. public _activeIndices = 0;
  193. public _activeParticles = 0;
  194. private _lastFrameDuration = 0;
  195. private _evaluateActiveMeshesDuration = 0;
  196. private _renderTargetsDuration = 0;
  197. public _particlesDuration = 0;
  198. private _renderDuration = 0;
  199. public _spritesDuration = 0;
  200. private _animationRatio = 0;
  201. private _animationStartDate: number;
  202. public _cachedMaterial: Material;
  203. private _renderId = 0;
  204. private _executeWhenReadyTimeoutId = -1;
  205. public _toBeDisposed = new SmartArray<IDisposable>(256);
  206. private _onReadyCallbacks = new Array<() => void>();
  207. private _pendingData = [];//ANY
  208. private _onBeforeRenderCallbacks = new Array<() => void>();
  209. private _onAfterRenderCallbacks = new Array<() => void>();
  210. private _activeMeshes = new SmartArray<Mesh>(256);
  211. private _processedMaterials = new SmartArray<Material>(256);
  212. private _renderTargets = new SmartArray<RenderTargetTexture>(256);
  213. public _activeParticleSystems = new SmartArray<ParticleSystem>(256);
  214. private _activeSkeletons = new SmartArray<Skeleton>(32);
  215. private _softwareSkinnedMeshes = new SmartArray<Mesh>(32);
  216. public _activeBones = 0;
  217. private _renderingManager: RenderingManager;
  218. private _physicsEngine: PhysicsEngine;
  219. public _activeAnimatables = new Array<Animatable>();
  220. private _transformMatrix = Matrix.Zero();
  221. private _pickWithRayInverseMatrix: Matrix;
  222. private _edgesRenderers = new SmartArray<EdgesRenderer>(16);
  223. private _boundingBoxRenderer: BoundingBoxRenderer;
  224. private _outlineRenderer: OutlineRenderer;
  225. private _viewMatrix: Matrix;
  226. private _projectionMatrix: Matrix;
  227. private _frustumPlanes: Plane[];
  228. private _selectionOctree: Octree<AbstractMesh>;
  229. private _pointerOverMesh: AbstractMesh;
  230. private _debugLayer: DebugLayer;
  231. private _depthRenderer: DepthRenderer;
  232. private _uniqueIdCounter = 0;
  233. private _pickedMeshName : string = null;
  234. /**
  235. * @constructor
  236. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  237. */
  238. constructor(engine: Engine) {
  239. this._engine = engine;
  240. engine.scenes.push(this);
  241. this._renderingManager = new RenderingManager(this);
  242. this.postProcessManager = new PostProcessManager(this);
  243. this.postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  244. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  245. if (OutlineRenderer) {
  246. this._outlineRenderer = new OutlineRenderer(this);
  247. }
  248. this.attachControl();
  249. this._debugLayer = new DebugLayer(this);
  250. if (SoundTrack) {
  251. this.mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  252. }
  253. //simplification queue
  254. if (SimplificationQueue) {
  255. this.simplificationQueue = new SimplificationQueue();
  256. }
  257. //collision coordinator initialization. For now legacy per default.
  258. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  259. }
  260. // Properties
  261. public get debugLayer(): DebugLayer {
  262. return this._debugLayer;
  263. }
  264. public set workerCollisions(enabled: boolean) {
  265. enabled = (enabled && !!Worker);
  266. this._workerCollisions = enabled;
  267. if (this.collisionCoordinator) {
  268. this.collisionCoordinator.destroy();
  269. }
  270. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  271. this.collisionCoordinator.init(this);
  272. }
  273. public get workerCollisions(): boolean {
  274. return this._workerCollisions;
  275. }
  276. public get SelectionOctree(): Octree<AbstractMesh> {
  277. return this._selectionOctree;
  278. }
  279. /**
  280. * The mesh that is currently under the pointer.
  281. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  282. */
  283. public get meshUnderPointer(): AbstractMesh {
  284. return this._meshUnderPointer;
  285. }
  286. /**
  287. * Current on-screen X position of the pointer
  288. * @return {number} X position of the pointer
  289. */
  290. public get pointerX(): number {
  291. return this._pointerX;
  292. }
  293. /**
  294. * Current on-screen Y position of the pointer
  295. * @return {number} Y position of the pointer
  296. */
  297. public get pointerY(): number {
  298. return this._pointerY;
  299. }
  300. public getCachedMaterial(): Material {
  301. return this._cachedMaterial;
  302. }
  303. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  304. return this._boundingBoxRenderer;
  305. }
  306. public getOutlineRenderer(): OutlineRenderer {
  307. return this._outlineRenderer;
  308. }
  309. public getEngine(): Engine {
  310. return this._engine;
  311. }
  312. public getTotalVertices(): number {
  313. return this._totalVertices;
  314. }
  315. public getActiveIndices(): number {
  316. return this._activeIndices;
  317. }
  318. public getActiveParticles(): number {
  319. return this._activeParticles;
  320. }
  321. public getActiveBones(): number {
  322. return this._activeBones;
  323. }
  324. // Stats
  325. public getLastFrameDuration(): number {
  326. return this._lastFrameDuration;
  327. }
  328. public getEvaluateActiveMeshesDuration(): number {
  329. return this._evaluateActiveMeshesDuration;
  330. }
  331. public getActiveMeshes(): SmartArray<Mesh> {
  332. return this._activeMeshes;
  333. }
  334. public getRenderTargetsDuration(): number {
  335. return this._renderTargetsDuration;
  336. }
  337. public getRenderDuration(): number {
  338. return this._renderDuration;
  339. }
  340. public getParticlesDuration(): number {
  341. return this._particlesDuration;
  342. }
  343. public getSpritesDuration(): number {
  344. return this._spritesDuration;
  345. }
  346. public getAnimationRatio(): number {
  347. return this._animationRatio;
  348. }
  349. public getRenderId(): number {
  350. return this._renderId;
  351. }
  352. public incrementRenderId(): void {
  353. this._renderId++;
  354. }
  355. private _updatePointerPosition(evt: PointerEvent): void {
  356. var canvasRect = this._engine.getRenderingCanvasClientRect();
  357. this._pointerX = evt.clientX - canvasRect.left;
  358. this._pointerY = evt.clientY - canvasRect.top;
  359. if (this.cameraToUseForPointers) {
  360. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  361. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  362. }
  363. }
  364. // Pointers handling
  365. public attachControl() {
  366. var spritePredicate = (sprite: Sprite): boolean => {
  367. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  368. };
  369. this._onPointerMove = (evt: PointerEvent) => {
  370. if (!this.cameraToUseForPointers && !this.activeCamera) {
  371. return;
  372. }
  373. var canvas = this._engine.getRenderingCanvas();
  374. this._updatePointerPosition(evt);
  375. // Meshes
  376. var pickResult = this.pick(this._pointerX, this._pointerY,
  377. (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && (this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined),
  378. false,
  379. this.cameraToUseForPointers);
  380. if (pickResult.hit && pickResult.pickedMesh) {
  381. this._meshUnderPointer = pickResult.pickedMesh;
  382. this.setPointerOverMesh(pickResult.pickedMesh);
  383. if (this._meshUnderPointer.actionManager && this._meshUnderPointer.actionManager.hasPointerTriggers) {
  384. canvas.style.cursor = "pointer";
  385. } else {
  386. canvas.style.cursor = "";
  387. }
  388. } else {
  389. // Sprites
  390. pickResult = this.pickSprite(this._pointerX, this._pointerY, spritePredicate, false, this.cameraToUseForPointers);
  391. if (pickResult.hit && pickResult.pickedSprite) {
  392. canvas.style.cursor = "pointer";
  393. } else {
  394. // Restore pointer
  395. this.setPointerOverMesh(null);
  396. canvas.style.cursor = "";
  397. this._meshUnderPointer = null;
  398. }
  399. }
  400. if (this.onPointerMove) {
  401. this.onPointerMove(evt, pickResult);
  402. }
  403. };
  404. this._onPointerDown = (evt: PointerEvent) => {
  405. if (!this.cameraToUseForPointers && !this.activeCamera) {
  406. return;
  407. }
  408. this._updatePointerPosition(evt);
  409. this._pickedMeshName = null;
  410. this._startingPointerPosition.x = this._pointerX;
  411. this._startingPointerPosition.y = this._pointerY;
  412. this._startingPointerTime = new Date().getTime();
  413. var predicate = null;
  414. // Meshes
  415. if (!this.onPointerDown && !this.onPointerDownUp) {
  416. predicate = (mesh: AbstractMesh): boolean => {
  417. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  418. };
  419. }
  420. var pickResult = this.pick(this._pointerX, this._pointerY, predicate, false, this.cameraToUseForPointers);
  421. if (pickResult.hit && pickResult.pickedMesh) {
  422. this._pickedMeshName = pickResult.pickedMesh.name;
  423. if (pickResult.pickedMesh.actionManager) {
  424. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  425. switch (evt.button) {
  426. case 0:
  427. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  428. break;
  429. case 1:
  430. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  431. break;
  432. case 2:
  433. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  434. break;
  435. }
  436. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  437. }
  438. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger)) {
  439. var that = this;
  440. window.setTimeout(function () {
  441. var pickResult = that.pick(that._pointerX, that._pointerY,
  442. (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger),
  443. false, that.cameraToUseForPointers);
  444. if (pickResult.hit && pickResult.pickedMesh) {
  445. if (pickResult.pickedMesh.actionManager) {
  446. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < ActionManager.DragMovementThreshold)) {
  447. that._startingPointerTime = 0;
  448. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  449. }
  450. }
  451. }
  452. }, ActionManager.LongPressDelay);
  453. }
  454. }
  455. }
  456. if (this.onPointerDown) {
  457. this.onPointerDown(evt, pickResult);
  458. }
  459. // Sprites
  460. if (this.spriteManagers.length > 0) {
  461. pickResult = this.pickSprite(this._pointerX, this._pointerY, spritePredicate, false, this.cameraToUseForPointers);
  462. if (pickResult.hit && pickResult.pickedSprite) {
  463. if (pickResult.pickedSprite.actionManager) {
  464. switch (evt.button) {
  465. case 0:
  466. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  467. break;
  468. case 1:
  469. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  470. break;
  471. case 2:
  472. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  473. break;
  474. }
  475. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  476. }
  477. }
  478. }
  479. };
  480. this._onPointerUp = (evt: PointerEvent) => {
  481. if (!this.cameraToUseForPointers && !this.activeCamera) {
  482. return;
  483. }
  484. var predicate = null;
  485. this._updatePointerPosition(evt);
  486. if (!this.onPointerUp && !this.onPointerDownUp) {
  487. predicate = (mesh: AbstractMesh): boolean => {
  488. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger));
  489. };
  490. }
  491. // Meshes
  492. var pickResult = this.pick(this._pointerX, this._pointerY, predicate, false, this.cameraToUseForPointers);
  493. if (pickResult.hit && pickResult.pickedMesh) {
  494. if(this.onPointerDownUp && this._pickedMeshName != null && pickResult.pickedMesh.name == this._pickedMeshName){
  495. this.onPointerDownUp(evt, pickResult);
  496. }
  497. if (pickResult.pickedMesh.actionManager) {
  498. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  499. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < ActionManager.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < ActionManager.DragMovementThreshold) {
  500. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  501. }
  502. }
  503. }
  504. if (this.onPointerUp) {
  505. this.onPointerUp(evt, pickResult);
  506. }
  507. this._startingPointerTime = 0;
  508. // Sprites
  509. if (this.spriteManagers.length > 0) {
  510. pickResult = this.pickSprite(this._pointerX, this._pointerY, spritePredicate, false, this.cameraToUseForPointers);
  511. if (pickResult.hit && pickResult.pickedSprite) {
  512. if (pickResult.pickedSprite.actionManager) {
  513. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  514. }
  515. }
  516. }
  517. };
  518. this._onKeyDown = (evt: Event) => {
  519. if (this.actionManager) {
  520. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  521. }
  522. };
  523. this._onKeyUp = (evt: Event) => {
  524. if (this.actionManager) {
  525. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  526. }
  527. };
  528. var eventPrefix = Tools.GetPointerPrefix();
  529. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  530. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  531. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  532. // Wheel
  533. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  534. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  535. Tools.RegisterTopRootEvents([
  536. { name: "keydown", handler: this._onKeyDown },
  537. { name: "keyup", handler: this._onKeyUp }
  538. ]);
  539. }
  540. public detachControl() {
  541. var eventPrefix = Tools.GetPointerPrefix();
  542. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  543. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  544. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  545. // Wheel
  546. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  547. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  548. Tools.UnregisterTopRootEvents([
  549. { name: "keydown", handler: this._onKeyDown },
  550. { name: "keyup", handler: this._onKeyUp }
  551. ]);
  552. }
  553. // Ready
  554. public isReady(): boolean {
  555. if (this._pendingData.length > 0) {
  556. return false;
  557. }
  558. var index: number;
  559. for (index = 0; index < this._geometries.length; index++) {
  560. var geometry = this._geometries[index];
  561. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  562. return false;
  563. }
  564. }
  565. for (index = 0; index < this.meshes.length; index++) {
  566. var mesh = this.meshes[index];
  567. if (!mesh.isReady()) {
  568. return false;
  569. }
  570. var mat = mesh.material;
  571. if (mat) {
  572. if (!mat.isReady(mesh)) {
  573. return false;
  574. }
  575. }
  576. }
  577. return true;
  578. }
  579. public resetCachedMaterial(): void {
  580. this._cachedMaterial = null;
  581. }
  582. public registerBeforeRender(func: () => void): void {
  583. this._onBeforeRenderCallbacks.push(func);
  584. }
  585. public unregisterBeforeRender(func: () => void): void {
  586. var index = this._onBeforeRenderCallbacks.indexOf(func);
  587. if (index > -1) {
  588. this._onBeforeRenderCallbacks.splice(index, 1);
  589. }
  590. }
  591. public registerAfterRender(func: () => void): void {
  592. this._onAfterRenderCallbacks.push(func);
  593. }
  594. public unregisterAfterRender(func: () => void): void {
  595. var index = this._onAfterRenderCallbacks.indexOf(func);
  596. if (index > -1) {
  597. this._onAfterRenderCallbacks.splice(index, 1);
  598. }
  599. }
  600. public _addPendingData(data): void {
  601. this._pendingData.push(data);
  602. }
  603. public _removePendingData(data): void {
  604. var index = this._pendingData.indexOf(data);
  605. if (index !== -1) {
  606. this._pendingData.splice(index, 1);
  607. }
  608. }
  609. public getWaitingItemsCount(): number {
  610. return this._pendingData.length;
  611. }
  612. /**
  613. * Registers a function to be executed when the scene is ready.
  614. * @param {Function} func - the function to be executed.
  615. */
  616. public executeWhenReady(func: () => void): void {
  617. this._onReadyCallbacks.push(func);
  618. if (this._executeWhenReadyTimeoutId !== -1) {
  619. return;
  620. }
  621. this._executeWhenReadyTimeoutId = setTimeout(() => {
  622. this._checkIsReady();
  623. }, 150);
  624. }
  625. public _checkIsReady() {
  626. if (this.isReady()) {
  627. this._onReadyCallbacks.forEach(func => {
  628. func();
  629. });
  630. this._onReadyCallbacks = [];
  631. this._executeWhenReadyTimeoutId = -1;
  632. return;
  633. }
  634. this._executeWhenReadyTimeoutId = setTimeout(() => {
  635. this._checkIsReady();
  636. }, 150);
  637. }
  638. // Animations
  639. /**
  640. * Will start the animation sequence of a given target
  641. * @param target - the target
  642. * @param {number} from - from which frame should animation start
  643. * @param {number} to - till which frame should animation run.
  644. * @param {boolean} [loop] - should the animation loop
  645. * @param {number} [speedRatio] - the speed in which to run the animation
  646. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  647. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  648. * @return {BABYLON.Animatable} the animatable object created for this animation
  649. * @see BABYLON.Animatable
  650. * @see http://doc.babylonjs.com/page.php?p=22081
  651. */
  652. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  653. this.stopAnimation(target);
  654. if (!animatable) {
  655. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  656. }
  657. // Local animations
  658. if (target.animations) {
  659. animatable.appendAnimations(target, target.animations);
  660. }
  661. // Children animations
  662. if (target.getAnimatables) {
  663. var animatables = target.getAnimatables();
  664. for (var index = 0; index < animatables.length; index++) {
  665. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  666. }
  667. }
  668. return animatable;
  669. }
  670. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  671. if (speedRatio === undefined) {
  672. speedRatio = 1.0;
  673. }
  674. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  675. return animatable;
  676. }
  677. public getAnimatableByTarget(target: any): Animatable {
  678. for (var index = 0; index < this._activeAnimatables.length; index++) {
  679. if (this._activeAnimatables[index].target === target) {
  680. return this._activeAnimatables[index];
  681. }
  682. }
  683. return null;
  684. }
  685. public get Animatables(): Animatable[] {
  686. return this._activeAnimatables;
  687. }
  688. /**
  689. * Will stop the animation of the given target
  690. * @param target - the target
  691. * @see beginAnimation
  692. */
  693. public stopAnimation(target: any): void {
  694. var animatable = this.getAnimatableByTarget(target);
  695. if (animatable) {
  696. animatable.stop();
  697. }
  698. }
  699. private _animate(): void {
  700. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  701. return;
  702. }
  703. if (!this._animationStartDate) {
  704. if (this._pendingData.length > 0) {
  705. return;
  706. }
  707. this._animationStartDate = Tools.Now;
  708. }
  709. // Getting time
  710. var now = Tools.Now;
  711. var delay = now - this._animationStartDate;
  712. for (var index = 0; index < this._activeAnimatables.length; index++) {
  713. this._activeAnimatables[index]._animate(delay);
  714. }
  715. }
  716. // Matrix
  717. public getViewMatrix(): Matrix {
  718. return this._viewMatrix;
  719. }
  720. public getProjectionMatrix(): Matrix {
  721. return this._projectionMatrix;
  722. }
  723. public getTransformMatrix(): Matrix {
  724. return this._transformMatrix;
  725. }
  726. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  727. this._viewMatrix = view;
  728. this._projectionMatrix = projection;
  729. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  730. }
  731. // Methods
  732. public addMesh(newMesh: AbstractMesh) {
  733. newMesh.uniqueId = this._uniqueIdCounter++;
  734. var position = this.meshes.push(newMesh);
  735. //notify the collision coordinator
  736. this.collisionCoordinator.onMeshAdded(newMesh);
  737. if (this.onNewMeshAdded) {
  738. this.onNewMeshAdded(newMesh, position, this);
  739. }
  740. }
  741. public removeMesh(toRemove: AbstractMesh): number {
  742. var index = this.meshes.indexOf(toRemove);
  743. if (index !== -1) {
  744. // Remove from the scene if mesh found
  745. this.meshes.splice(index, 1);
  746. }
  747. //notify the collision coordinator
  748. this.collisionCoordinator.onMeshRemoved(toRemove);
  749. if (this.onMeshRemoved) {
  750. this.onMeshRemoved(toRemove);
  751. }
  752. return index;
  753. }
  754. public removeSkeleton(toRemove: Skeleton): number {
  755. var index = this.skeletons.indexOf(toRemove);
  756. if (index !== -1) {
  757. // Remove from the scene if mesh found
  758. this.skeletons.splice(index, 1);
  759. }
  760. return index;
  761. }
  762. public removeLight(toRemove: Light): number {
  763. var index = this.lights.indexOf(toRemove);
  764. if (index !== -1) {
  765. // Remove from the scene if mesh found
  766. this.lights.splice(index, 1);
  767. }
  768. if (this.onLightRemoved) {
  769. this.onLightRemoved(toRemove);
  770. }
  771. return index;
  772. }
  773. public removeCamera(toRemove: Camera): number {
  774. var index = this.cameras.indexOf(toRemove);
  775. if (index !== -1) {
  776. // Remove from the scene if mesh found
  777. this.cameras.splice(index, 1);
  778. }
  779. // Remove from activeCameras
  780. var index2 = this.activeCameras.indexOf(toRemove);
  781. if (index2 !== -1) {
  782. // Remove from the scene if mesh found
  783. this.activeCameras.splice(index2, 1);
  784. }
  785. // Reset the activeCamera
  786. if (this.activeCamera === toRemove) {
  787. if (this.cameras.length > 0) {
  788. this.activeCamera = this.cameras[0];
  789. } else {
  790. this.activeCamera = null;
  791. }
  792. }
  793. if (this.onCameraRemoved) {
  794. this.onCameraRemoved(toRemove);
  795. }
  796. return index;
  797. }
  798. public addLight(newLight: Light) {
  799. newLight.uniqueId = this._uniqueIdCounter++;
  800. var position = this.lights.push(newLight);
  801. if (this.onNewLightAdded) {
  802. this.onNewLightAdded(newLight, position, this);
  803. }
  804. }
  805. public addCamera(newCamera: Camera) {
  806. newCamera.uniqueId = this._uniqueIdCounter++;
  807. var position = this.cameras.push(newCamera);
  808. if (this.onNewCameraAdded) {
  809. this.onNewCameraAdded(newCamera, position, this);
  810. }
  811. }
  812. /**
  813. * sets the active camera of the scene using its ID
  814. * @param {string} id - the camera's ID
  815. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  816. * @see activeCamera
  817. */
  818. public setActiveCameraByID(id: string): Camera {
  819. var camera = this.getCameraByID(id);
  820. if (camera) {
  821. this.activeCamera = camera;
  822. return camera;
  823. }
  824. return null;
  825. }
  826. /**
  827. * sets the active camera of the scene using its name
  828. * @param {string} name - the camera's name
  829. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  830. * @see activeCamera
  831. */
  832. public setActiveCameraByName(name: string): Camera {
  833. var camera = this.getCameraByName(name);
  834. if (camera) {
  835. this.activeCamera = camera;
  836. return camera;
  837. }
  838. return null;
  839. }
  840. /**
  841. * get a material using its id
  842. * @param {string} the material's ID
  843. * @return {BABYLON.Material|null} the material or null if none found.
  844. */
  845. public getMaterialByID(id: string): Material {
  846. for (var index = 0; index < this.materials.length; index++) {
  847. if (this.materials[index].id === id) {
  848. return this.materials[index];
  849. }
  850. }
  851. return null;
  852. }
  853. /**
  854. * get a material using its name
  855. * @param {string} the material's name
  856. * @return {BABYLON.Material|null} the material or null if none found.
  857. */
  858. public getMaterialByName(name: string): Material {
  859. for (var index = 0; index < this.materials.length; index++) {
  860. if (this.materials[index].name === name) {
  861. return this.materials[index];
  862. }
  863. }
  864. return null;
  865. }
  866. public getLensFlareSystemByName(name: string): LensFlareSystem {
  867. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  868. if (this.lensFlareSystems[index].name === name) {
  869. return this.lensFlareSystems[index];
  870. }
  871. }
  872. return null;
  873. }
  874. public getCameraByID(id: string): Camera {
  875. for (var index = 0; index < this.cameras.length; index++) {
  876. if (this.cameras[index].id === id) {
  877. return this.cameras[index];
  878. }
  879. }
  880. return null;
  881. }
  882. public getCameraByUniqueID(uniqueId: number): Camera {
  883. for (var index = 0; index < this.cameras.length; index++) {
  884. if (this.cameras[index].uniqueId === uniqueId) {
  885. return this.cameras[index];
  886. }
  887. }
  888. return null;
  889. }
  890. /**
  891. * get a camera using its name
  892. * @param {string} the camera's name
  893. * @return {BABYLON.Camera|null} the camera or null if none found.
  894. */
  895. public getCameraByName(name: string): Camera {
  896. for (var index = 0; index < this.cameras.length; index++) {
  897. if (this.cameras[index].name === name) {
  898. return this.cameras[index];
  899. }
  900. }
  901. return null;
  902. }
  903. /**
  904. * get a bone using its id
  905. * @param {string} the bone's id
  906. * @return {BABYLON.Bone|null} the bone or null if not found
  907. */
  908. public getBoneByID(id: string): Bone {
  909. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  910. var skeleton = this.skeletons[skeletonIndex];
  911. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  912. if (skeleton.bones[boneIndex].id === id) {
  913. return skeleton.bones[boneIndex];
  914. }
  915. }
  916. }
  917. return null;
  918. }
  919. /**
  920. * get a bone using its id
  921. * @param {string} the bone's name
  922. * @return {BABYLON.Bone|null} the bone or null if not found
  923. */
  924. public getBoneByName(name: string): Bone {
  925. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  926. var skeleton = this.skeletons[skeletonIndex];
  927. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  928. if (skeleton.bones[boneIndex].name === name) {
  929. return skeleton.bones[boneIndex];
  930. }
  931. }
  932. }
  933. return null;
  934. }
  935. /**
  936. * get a light node using its name
  937. * @param {string} the light's name
  938. * @return {BABYLON.Light|null} the light or null if none found.
  939. */
  940. public getLightByName(name: string): Light {
  941. for (var index = 0; index < this.lights.length; index++) {
  942. if (this.lights[index].name === name) {
  943. return this.lights[index];
  944. }
  945. }
  946. return null;
  947. }
  948. /**
  949. * get a light node using its ID
  950. * @param {string} the light's id
  951. * @return {BABYLON.Light|null} the light or null if none found.
  952. */
  953. public getLightByID(id: string): Light {
  954. for (var index = 0; index < this.lights.length; index++) {
  955. if (this.lights[index].id === id) {
  956. return this.lights[index];
  957. }
  958. }
  959. return null;
  960. }
  961. /**
  962. * get a light node using its scene-generated unique ID
  963. * @param {number} the light's unique id
  964. * @return {BABYLON.Light|null} the light or null if none found.
  965. */
  966. public getLightByUniqueID(uniqueId: number): Light {
  967. for (var index = 0; index < this.lights.length; index++) {
  968. if (this.lights[index].uniqueId === uniqueId) {
  969. return this.lights[index];
  970. }
  971. }
  972. return null;
  973. }
  974. /**
  975. * get a particle system by id
  976. * @param id {number} the particle system id
  977. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  978. */
  979. public getParticleSystemByID(id: string): ParticleSystem {
  980. for (var index = 0; index < this.particleSystems.length; index++) {
  981. if (this.particleSystems[index].id === id) {
  982. return this.particleSystems[index];
  983. }
  984. }
  985. return null;
  986. }
  987. /**
  988. * get a geometry using its ID
  989. * @param {string} the geometry's id
  990. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  991. */
  992. public getGeometryByID(id: string): Geometry {
  993. for (var index = 0; index < this._geometries.length; index++) {
  994. if (this._geometries[index].id === id) {
  995. return this._geometries[index];
  996. }
  997. }
  998. return null;
  999. }
  1000. /**
  1001. * add a new geometry to this scene.
  1002. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  1003. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  1004. * @return {boolean} was the geometry added or not
  1005. */
  1006. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  1007. if (!force && this.getGeometryByID(geometry.id)) {
  1008. return false;
  1009. }
  1010. this._geometries.push(geometry);
  1011. //notify the collision coordinator
  1012. this.collisionCoordinator.onGeometryAdded(geometry);
  1013. if (this.onGeometryAdded) {
  1014. this.onGeometryAdded(geometry);
  1015. }
  1016. return true;
  1017. }
  1018. /**
  1019. * Removes an existing geometry
  1020. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  1021. * @return {boolean} was the geometry removed or not
  1022. */
  1023. public removeGeometry(geometry: Geometry): boolean {
  1024. var index = this._geometries.indexOf(geometry);
  1025. if (index > -1) {
  1026. this._geometries.splice(index, 1);
  1027. //notify the collision coordinator
  1028. this.collisionCoordinator.onGeometryDeleted(geometry);
  1029. if (this.onGeometryRemoved) {
  1030. this.onGeometryRemoved(geometry);
  1031. }
  1032. return true;
  1033. }
  1034. return false;
  1035. }
  1036. public getGeometries(): Geometry[] {
  1037. return this._geometries;
  1038. }
  1039. /**
  1040. * Get the first added mesh found of a given ID
  1041. * @param {string} id - the id to search for
  1042. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1043. */
  1044. public getMeshByID(id: string): AbstractMesh {
  1045. for (var index = 0; index < this.meshes.length; index++) {
  1046. if (this.meshes[index].id === id) {
  1047. return this.meshes[index];
  1048. }
  1049. }
  1050. return null;
  1051. }
  1052. /**
  1053. * Get a mesh with its auto-generated unique id
  1054. * @param {number} uniqueId - the unique id to search for
  1055. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1056. */
  1057. public getMeshByUniqueID(uniqueId: number): AbstractMesh {
  1058. for (var index = 0; index < this.meshes.length; index++) {
  1059. if (this.meshes[index].uniqueId === uniqueId) {
  1060. return this.meshes[index];
  1061. }
  1062. }
  1063. return null;
  1064. }
  1065. /**
  1066. * Get a the last added mesh found of a given ID
  1067. * @param {string} id - the id to search for
  1068. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1069. */
  1070. public getLastMeshByID(id: string): AbstractMesh {
  1071. for (var index = this.meshes.length - 1; index >= 0; index--) {
  1072. if (this.meshes[index].id === id) {
  1073. return this.meshes[index];
  1074. }
  1075. }
  1076. return null;
  1077. }
  1078. /**
  1079. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  1080. * @param {string} id - the id to search for
  1081. * @return {BABYLON.Node|null} the node found or null if not found at all.
  1082. */
  1083. public getLastEntryByID(id: string): Node {
  1084. var index: number;
  1085. for (index = this.meshes.length - 1; index >= 0; index--) {
  1086. if (this.meshes[index].id === id) {
  1087. return this.meshes[index];
  1088. }
  1089. }
  1090. for (index = this.cameras.length - 1; index >= 0; index--) {
  1091. if (this.cameras[index].id === id) {
  1092. return this.cameras[index];
  1093. }
  1094. }
  1095. for (index = this.lights.length - 1; index >= 0; index--) {
  1096. if (this.lights[index].id === id) {
  1097. return this.lights[index];
  1098. }
  1099. }
  1100. return null;
  1101. }
  1102. public getNodeByID(id: string): Node {
  1103. var mesh = this.getMeshByID(id);
  1104. if (mesh) {
  1105. return mesh;
  1106. }
  1107. var light = this.getLightByID(id);
  1108. if (light) {
  1109. return light;
  1110. }
  1111. var camera = this.getCameraByID(id);
  1112. if (camera) {
  1113. return camera;
  1114. }
  1115. var bone = this.getBoneByID(id);
  1116. return bone;
  1117. }
  1118. public getNodeByName(name: string): Node {
  1119. var mesh = this.getMeshByName(name);
  1120. if (mesh) {
  1121. return mesh;
  1122. }
  1123. var light = this.getLightByName(name);
  1124. if (light) {
  1125. return light;
  1126. }
  1127. var camera = this.getCameraByName(name);
  1128. if (camera) {
  1129. return camera;
  1130. }
  1131. var bone = this.getBoneByName(name);
  1132. return bone;
  1133. }
  1134. public getMeshByName(name: string): AbstractMesh {
  1135. for (var index = 0; index < this.meshes.length; index++) {
  1136. if (this.meshes[index].name === name) {
  1137. return this.meshes[index];
  1138. }
  1139. }
  1140. return null;
  1141. }
  1142. public getSoundByName(name: string): Sound {
  1143. var index: number;
  1144. if (AudioEngine) {
  1145. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  1146. if (this.mainSoundTrack.soundCollection[index].name === name) {
  1147. return this.mainSoundTrack.soundCollection[index];
  1148. }
  1149. }
  1150. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  1151. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  1152. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  1153. return this.soundTracks[sdIndex].soundCollection[index];
  1154. }
  1155. }
  1156. }
  1157. }
  1158. return null;
  1159. }
  1160. public getLastSkeletonByID(id: string): Skeleton {
  1161. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  1162. if (this.skeletons[index].id === id) {
  1163. return this.skeletons[index];
  1164. }
  1165. }
  1166. return null;
  1167. }
  1168. public getSkeletonById(id: string): Skeleton {
  1169. for (var index = 0; index < this.skeletons.length; index++) {
  1170. if (this.skeletons[index].id === id) {
  1171. return this.skeletons[index];
  1172. }
  1173. }
  1174. return null;
  1175. }
  1176. public getSkeletonByName(name: string): Skeleton {
  1177. for (var index = 0; index < this.skeletons.length; index++) {
  1178. if (this.skeletons[index].name === name) {
  1179. return this.skeletons[index];
  1180. }
  1181. }
  1182. return null;
  1183. }
  1184. public isActiveMesh(mesh: Mesh): boolean {
  1185. return (this._activeMeshes.indexOf(mesh) !== -1);
  1186. }
  1187. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  1188. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  1189. var material = subMesh.getMaterial();
  1190. if (mesh.showSubMeshesBoundingBox) {
  1191. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  1192. }
  1193. if (material) {
  1194. // Render targets
  1195. if (material.getRenderTargetTextures) {
  1196. if (this._processedMaterials.indexOf(material) === -1) {
  1197. this._processedMaterials.push(material);
  1198. this._renderTargets.concat(material.getRenderTargetTextures());
  1199. }
  1200. }
  1201. // Dispatch
  1202. this._activeIndices += subMesh.indexCount;
  1203. this._renderingManager.dispatch(subMesh);
  1204. }
  1205. }
  1206. }
  1207. private _evaluateActiveMeshes(): void {
  1208. this.activeCamera._activeMeshes.reset();
  1209. this._activeMeshes.reset();
  1210. this._renderingManager.reset();
  1211. this._processedMaterials.reset();
  1212. this._activeParticleSystems.reset();
  1213. this._activeSkeletons.reset();
  1214. this._softwareSkinnedMeshes.reset();
  1215. this._boundingBoxRenderer.reset();
  1216. this._edgesRenderers.reset();
  1217. if (!this._frustumPlanes) {
  1218. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  1219. } else {
  1220. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1221. }
  1222. // Meshes
  1223. var meshes: AbstractMesh[];
  1224. var len: number;
  1225. if (this._selectionOctree) { // Octree
  1226. var selection = this._selectionOctree.select(this._frustumPlanes);
  1227. meshes = selection.data;
  1228. len = selection.length;
  1229. } else { // Full scene traversal
  1230. len = this.meshes.length;
  1231. meshes = this.meshes;
  1232. }
  1233. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  1234. var mesh = meshes[meshIndex];
  1235. if (mesh.isBlocked) {
  1236. continue;
  1237. }
  1238. this._totalVertices += mesh.getTotalVertices();
  1239. if (!mesh.isReady() || !mesh.isEnabled()) {
  1240. continue;
  1241. }
  1242. mesh.computeWorldMatrix();
  1243. // Intersections
  1244. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  1245. this._meshesForIntersections.pushNoDuplicate(mesh);
  1246. }
  1247. // Switch to current LOD
  1248. var meshLOD = mesh.getLOD(this.activeCamera);
  1249. if (!meshLOD) {
  1250. continue;
  1251. }
  1252. mesh._preActivate();
  1253. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  1254. this._activeMeshes.push(mesh);
  1255. this.activeCamera._activeMeshes.push(mesh);
  1256. mesh._activate(this._renderId);
  1257. this._activeMesh(meshLOD);
  1258. }
  1259. }
  1260. // Particle systems
  1261. var beforeParticlesDate = Tools.Now;
  1262. if (this.particlesEnabled) {
  1263. Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  1264. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  1265. var particleSystem = this.particleSystems[particleIndex];
  1266. if (!particleSystem.isStarted()) {
  1267. continue;
  1268. }
  1269. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  1270. this._activeParticleSystems.push(particleSystem);
  1271. particleSystem.animate();
  1272. }
  1273. }
  1274. Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  1275. }
  1276. this._particlesDuration += Tools.Now - beforeParticlesDate;
  1277. }
  1278. private _activeMesh(mesh: AbstractMesh): void {
  1279. if (mesh.skeleton && this.skeletonsEnabled) {
  1280. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  1281. if (!mesh.computeBonesUsingShaders) {
  1282. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  1283. }
  1284. }
  1285. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  1286. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  1287. }
  1288. if (mesh._edgesRenderer) {
  1289. this._edgesRenderers.push(mesh._edgesRenderer);
  1290. }
  1291. if (mesh && mesh.subMeshes) {
  1292. // Submeshes Octrees
  1293. var len: number;
  1294. var subMeshes: SubMesh[];
  1295. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  1296. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  1297. len = intersections.length;
  1298. subMeshes = intersections.data;
  1299. } else {
  1300. subMeshes = mesh.subMeshes;
  1301. len = subMeshes.length;
  1302. }
  1303. for (var subIndex = 0; subIndex < len; subIndex++) {
  1304. var subMesh = subMeshes[subIndex];
  1305. this._evaluateSubMesh(subMesh, mesh);
  1306. }
  1307. }
  1308. }
  1309. public updateTransformMatrix(force?: boolean): void {
  1310. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  1311. }
  1312. private _renderForCamera(camera: Camera): void {
  1313. var engine = this._engine;
  1314. this.activeCamera = camera;
  1315. if (!this.activeCamera)
  1316. throw new Error("Active camera not set");
  1317. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  1318. // Viewport
  1319. engine.setViewport(this.activeCamera.viewport);
  1320. // Camera
  1321. this.resetCachedMaterial();
  1322. this._renderId++;
  1323. this.updateTransformMatrix();
  1324. if (this.beforeCameraRender) {
  1325. this.beforeCameraRender(this.activeCamera);
  1326. }
  1327. // Meshes
  1328. var beforeEvaluateActiveMeshesDate = Tools.Now;
  1329. Tools.StartPerformanceCounter("Active meshes evaluation");
  1330. this._evaluateActiveMeshes();
  1331. this._evaluateActiveMeshesDuration += Tools.Now - beforeEvaluateActiveMeshesDate;
  1332. Tools.EndPerformanceCounter("Active meshes evaluation");
  1333. // Skeletons
  1334. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  1335. var skeleton = this._activeSkeletons.data[skeletonIndex];
  1336. skeleton.prepare();
  1337. }
  1338. // Software skinning
  1339. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  1340. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  1341. mesh.applySkeleton(mesh.skeleton);
  1342. }
  1343. // Render targets
  1344. var beforeRenderTargetDate = Tools.Now;
  1345. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  1346. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  1347. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  1348. var renderTarget = this._renderTargets.data[renderIndex];
  1349. if (renderTarget._shouldRender()) {
  1350. this._renderId++;
  1351. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  1352. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  1353. }
  1354. }
  1355. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  1356. this._renderId++;
  1357. engine.restoreDefaultFramebuffer(); // Restore back buffer
  1358. }
  1359. this._renderTargetsDuration += Tools.Now - beforeRenderTargetDate;
  1360. // Prepare Frame
  1361. this.postProcessManager._prepareFrame();
  1362. var beforeRenderDate = Tools.Now;
  1363. // Backgrounds
  1364. var layerIndex;
  1365. var layer;
  1366. if (this.layers.length) {
  1367. engine.setDepthBuffer(false);
  1368. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  1369. layer = this.layers[layerIndex];
  1370. if (layer.isBackground) {
  1371. layer.render();
  1372. }
  1373. }
  1374. engine.setDepthBuffer(true);
  1375. }
  1376. // Render
  1377. Tools.StartPerformanceCounter("Main render");
  1378. this._renderingManager.render(null, null, true, true);
  1379. Tools.EndPerformanceCounter("Main render");
  1380. // Bounding boxes
  1381. this._boundingBoxRenderer.render();
  1382. // Edges
  1383. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  1384. this._edgesRenderers.data[edgesRendererIndex].render();
  1385. }
  1386. // Lens flares
  1387. if (this.lensFlaresEnabled) {
  1388. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  1389. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  1390. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  1391. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  1392. lensFlareSystem.render();
  1393. }
  1394. }
  1395. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  1396. }
  1397. // Foregrounds
  1398. if (this.layers.length) {
  1399. engine.setDepthBuffer(false);
  1400. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  1401. layer = this.layers[layerIndex];
  1402. if (!layer.isBackground) {
  1403. layer.render();
  1404. }
  1405. }
  1406. engine.setDepthBuffer(true);
  1407. }
  1408. this._renderDuration += Tools.Now - beforeRenderDate;
  1409. // Finalize frame
  1410. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  1411. // Update camera
  1412. this.activeCamera._updateFromScene();
  1413. // Reset some special arrays
  1414. this._renderTargets.reset();
  1415. if (this.afterCameraRender) {
  1416. this.afterCameraRender(this.activeCamera);
  1417. }
  1418. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  1419. }
  1420. private _processSubCameras(camera: Camera): void {
  1421. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  1422. this._renderForCamera(camera);
  1423. return;
  1424. }
  1425. // rig cameras
  1426. for (var index = 0; index < camera._rigCameras.length; index++) {
  1427. this._renderForCamera(camera._rigCameras[index]);
  1428. }
  1429. this.activeCamera = camera;
  1430. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  1431. // Update camera
  1432. this.activeCamera._updateFromScene();
  1433. }
  1434. private _checkIntersections(): void {
  1435. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  1436. var sourceMesh = this._meshesForIntersections.data[index];
  1437. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  1438. var action = sourceMesh.actionManager.actions[actionIndex];
  1439. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1440. var parameters = action.getTriggerParameter();
  1441. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  1442. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  1443. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  1444. if (areIntersecting && currentIntersectionInProgress === -1) {
  1445. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  1446. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  1447. sourceMesh._intersectionsInProgress.push(otherMesh);
  1448. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1449. sourceMesh._intersectionsInProgress.push(otherMesh);
  1450. }
  1451. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  1452. //They intersected, and now they don't.
  1453. //is this trigger an exit trigger? execute an event.
  1454. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1455. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  1456. }
  1457. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  1458. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1459. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  1460. }
  1461. }
  1462. }
  1463. }
  1464. }
  1465. }
  1466. public render(): void {
  1467. var startDate = Tools.Now;
  1468. this._particlesDuration = 0;
  1469. this._spritesDuration = 0;
  1470. this._activeParticles = 0;
  1471. this._renderDuration = 0;
  1472. this._renderTargetsDuration = 0;
  1473. this._evaluateActiveMeshesDuration = 0;
  1474. this._totalVertices = 0;
  1475. this._activeIndices = 0;
  1476. this._activeBones = 0;
  1477. this.getEngine().resetDrawCalls();
  1478. this._meshesForIntersections.reset();
  1479. this.resetCachedMaterial();
  1480. Tools.StartPerformanceCounter("Scene rendering");
  1481. // Actions
  1482. if (this.actionManager) {
  1483. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger, null);
  1484. }
  1485. //Simplification Queue
  1486. if (this.simplificationQueue && !this.simplificationQueue.running) {
  1487. this.simplificationQueue.executeNext();
  1488. }
  1489. // Animations
  1490. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  1491. this._animationRatio = deltaTime * (60.0 / 1000.0);
  1492. this._animate();
  1493. // Physics
  1494. if (this._physicsEngine) {
  1495. Tools.StartPerformanceCounter("Physics");
  1496. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  1497. Tools.EndPerformanceCounter("Physics");
  1498. }
  1499. // Before render
  1500. if (this.beforeRender) {
  1501. this.beforeRender();
  1502. }
  1503. var callbackIndex: number;
  1504. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  1505. this._onBeforeRenderCallbacks[callbackIndex]();
  1506. }
  1507. // Customs render targets
  1508. var beforeRenderTargetDate = Tools.Now;
  1509. var engine = this.getEngine();
  1510. var currentActiveCamera = this.activeCamera;
  1511. if (this.renderTargetsEnabled) {
  1512. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1513. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  1514. var renderTarget = this.customRenderTargets[customIndex];
  1515. if (renderTarget._shouldRender()) {
  1516. this._renderId++;
  1517. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  1518. if (!this.activeCamera)
  1519. throw new Error("Active camera not set");
  1520. // Viewport
  1521. engine.setViewport(this.activeCamera.viewport);
  1522. // Camera
  1523. this.updateTransformMatrix();
  1524. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  1525. }
  1526. }
  1527. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1528. this._renderId++;
  1529. }
  1530. if (this.customRenderTargets.length > 0) { // Restore back buffer
  1531. engine.restoreDefaultFramebuffer();
  1532. }
  1533. this._renderTargetsDuration += Tools.Now - beforeRenderTargetDate;
  1534. this.activeCamera = currentActiveCamera;
  1535. // Procedural textures
  1536. if (this.proceduralTexturesEnabled) {
  1537. Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1538. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  1539. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  1540. if (proceduralTexture._shouldRender()) {
  1541. proceduralTexture.render();
  1542. }
  1543. }
  1544. Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1545. }
  1546. // Clear
  1547. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  1548. // Shadows
  1549. if (this.shadowsEnabled) {
  1550. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  1551. var light = this.lights[lightIndex];
  1552. var shadowGenerator = light.getShadowGenerator();
  1553. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  1554. this._renderTargets.push(shadowGenerator.getShadowMap());
  1555. }
  1556. }
  1557. }
  1558. // Depth renderer
  1559. if (this._depthRenderer) {
  1560. this._renderTargets.push(this._depthRenderer.getDepthMap());
  1561. }
  1562. // RenderPipeline
  1563. this.postProcessRenderPipelineManager.update();
  1564. // Multi-cameras?
  1565. if (this.activeCameras.length > 0) {
  1566. var currentRenderId = this._renderId;
  1567. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  1568. this._renderId = currentRenderId;
  1569. if (cameraIndex > 0) {
  1570. this._engine.clear(0, false, true);
  1571. }
  1572. this._processSubCameras(this.activeCameras[cameraIndex]);
  1573. }
  1574. } else {
  1575. if (!this.activeCamera) {
  1576. throw new Error("No camera defined");
  1577. }
  1578. this._processSubCameras(this.activeCamera);
  1579. }
  1580. // Intersection checks
  1581. this._checkIntersections();
  1582. // Update the audio listener attached to the camera
  1583. if (AudioEngine) {
  1584. this._updateAudioParameters();
  1585. }
  1586. // After render
  1587. if (this.afterRender) {
  1588. this.afterRender();
  1589. }
  1590. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  1591. this._onAfterRenderCallbacks[callbackIndex]();
  1592. }
  1593. // Cleaning
  1594. for (var index = 0; index < this._toBeDisposed.length; index++) {
  1595. this._toBeDisposed.data[index].dispose();
  1596. this._toBeDisposed[index] = null;
  1597. }
  1598. this._toBeDisposed.reset();
  1599. if (this.dumpNextRenderTargets) {
  1600. this.dumpNextRenderTargets = false;
  1601. }
  1602. Tools.EndPerformanceCounter("Scene rendering");
  1603. this._lastFrameDuration = Tools.Now - startDate;
  1604. }
  1605. private _updateAudioParameters() {
  1606. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  1607. return;
  1608. }
  1609. var listeningCamera: Camera;
  1610. var audioEngine = Engine.audioEngine;
  1611. if (this.activeCameras.length > 0) {
  1612. listeningCamera = this.activeCameras[0];
  1613. } else {
  1614. listeningCamera = this.activeCamera;
  1615. }
  1616. if (listeningCamera && audioEngine.canUseWebAudio) {
  1617. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  1618. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  1619. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  1620. cameraDirection.normalize();
  1621. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  1622. var i: number;
  1623. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1624. var sound = this.mainSoundTrack.soundCollection[i];
  1625. if (sound.useCustomAttenuation) {
  1626. sound.updateDistanceFromListener();
  1627. }
  1628. }
  1629. for (i = 0; i < this.soundTracks.length; i++) {
  1630. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1631. sound = this.soundTracks[i].soundCollection[j];
  1632. if (sound.useCustomAttenuation) {
  1633. sound.updateDistanceFromListener();
  1634. }
  1635. }
  1636. }
  1637. }
  1638. }
  1639. // Audio
  1640. public get audioEnabled(): boolean {
  1641. return this._audioEnabled;
  1642. }
  1643. public set audioEnabled(value: boolean) {
  1644. this._audioEnabled = value;
  1645. if (AudioEngine) {
  1646. if (this._audioEnabled) {
  1647. this._enableAudio();
  1648. }
  1649. else {
  1650. this._disableAudio();
  1651. }
  1652. }
  1653. }
  1654. private _disableAudio() {
  1655. var i: number;
  1656. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1657. this.mainSoundTrack.soundCollection[i].pause();
  1658. }
  1659. for (i = 0; i < this.soundTracks.length; i++) {
  1660. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1661. this.soundTracks[i].soundCollection[j].pause();
  1662. }
  1663. }
  1664. }
  1665. private _enableAudio() {
  1666. var i: number;
  1667. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1668. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  1669. this.mainSoundTrack.soundCollection[i].play();
  1670. }
  1671. }
  1672. for (i = 0; i < this.soundTracks.length; i++) {
  1673. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1674. if (this.soundTracks[i].soundCollection[j].isPaused) {
  1675. this.soundTracks[i].soundCollection[j].play();
  1676. }
  1677. }
  1678. }
  1679. }
  1680. public get headphone(): boolean {
  1681. return this._headphone;
  1682. }
  1683. public set headphone(value: boolean) {
  1684. this._headphone = value;
  1685. if (AudioEngine) {
  1686. if (this._headphone) {
  1687. this._switchAudioModeForHeadphones();
  1688. }
  1689. else {
  1690. this._switchAudioModeForNormalSpeakers();
  1691. }
  1692. }
  1693. }
  1694. private _switchAudioModeForHeadphones() {
  1695. this.mainSoundTrack.switchPanningModelToHRTF();
  1696. for (var i = 0; i < this.soundTracks.length; i++) {
  1697. this.soundTracks[i].switchPanningModelToHRTF();
  1698. }
  1699. }
  1700. private _switchAudioModeForNormalSpeakers() {
  1701. this.mainSoundTrack.switchPanningModelToEqualPower();
  1702. for (var i = 0; i < this.soundTracks.length; i++) {
  1703. this.soundTracks[i].switchPanningModelToEqualPower();
  1704. }
  1705. }
  1706. public enableDepthRenderer(): DepthRenderer {
  1707. if (this._depthRenderer) {
  1708. return this._depthRenderer;
  1709. }
  1710. this._depthRenderer = new DepthRenderer(this);
  1711. return this._depthRenderer;
  1712. }
  1713. public disableDepthRenderer(): void {
  1714. if (!this._depthRenderer) {
  1715. return;
  1716. }
  1717. this._depthRenderer.dispose();
  1718. this._depthRenderer = null;
  1719. }
  1720. public freezeMaterials(): void {
  1721. for (var i = 0; i < this.materials.length; i++) {
  1722. this.materials[i].freeze();
  1723. }
  1724. }
  1725. public unfreezeMaterials(): void {
  1726. for (var i = 0; i < this.materials.length; i++) {
  1727. this.materials[i].unfreeze();
  1728. }
  1729. }
  1730. public dispose(): void {
  1731. this.beforeRender = null;
  1732. this.afterRender = null;
  1733. this.skeletons = [];
  1734. this._boundingBoxRenderer.dispose();
  1735. if (this._depthRenderer) {
  1736. this._depthRenderer.dispose();
  1737. }
  1738. // Debug layer
  1739. this.debugLayer.hide();
  1740. // Events
  1741. if (this.onDispose) {
  1742. this.onDispose();
  1743. }
  1744. this._onBeforeRenderCallbacks = [];
  1745. this._onAfterRenderCallbacks = [];
  1746. this.detachControl();
  1747. // Release sounds & sounds tracks
  1748. if (AudioEngine) {
  1749. this.disposeSounds();
  1750. }
  1751. // Detach cameras
  1752. var canvas = this._engine.getRenderingCanvas();
  1753. var index;
  1754. for (index = 0; index < this.cameras.length; index++) {
  1755. this.cameras[index].detachControl(canvas);
  1756. }
  1757. // Release lights
  1758. while (this.lights.length) {
  1759. this.lights[0].dispose();
  1760. }
  1761. // Release meshes
  1762. while (this.meshes.length) {
  1763. this.meshes[0].dispose(true);
  1764. }
  1765. // Release cameras
  1766. while (this.cameras.length) {
  1767. this.cameras[0].dispose();
  1768. }
  1769. // Release materials
  1770. while (this.materials.length) {
  1771. this.materials[0].dispose();
  1772. }
  1773. // Release particles
  1774. while (this.particleSystems.length) {
  1775. this.particleSystems[0].dispose();
  1776. }
  1777. // Release sprites
  1778. while (this.spriteManagers.length) {
  1779. this.spriteManagers[0].dispose();
  1780. }
  1781. // Release layers
  1782. while (this.layers.length) {
  1783. this.layers[0].dispose();
  1784. }
  1785. // Release textures
  1786. while (this.textures.length) {
  1787. this.textures[0].dispose();
  1788. }
  1789. // Post-processes
  1790. this.postProcessManager.dispose();
  1791. // Physics
  1792. if (this._physicsEngine) {
  1793. this.disablePhysicsEngine();
  1794. }
  1795. // Remove from engine
  1796. index = this._engine.scenes.indexOf(this);
  1797. if (index > -1) {
  1798. this._engine.scenes.splice(index, 1);
  1799. }
  1800. this._engine.wipeCaches();
  1801. }
  1802. // Release sounds & sounds tracks
  1803. public disposeSounds() {
  1804. this.mainSoundTrack.dispose();
  1805. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  1806. this.soundTracks[scIndex].dispose();
  1807. }
  1808. }
  1809. // Octrees
  1810. public getWorldExtends(): { min: Vector3; max: Vector3 } {
  1811. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1812. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1813. for (var index = 0; index < this.meshes.length; index++) {
  1814. var mesh = this.meshes[index];
  1815. mesh.computeWorldMatrix(true);
  1816. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  1817. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  1818. Tools.CheckExtends(minBox, min, max);
  1819. Tools.CheckExtends(maxBox, min, max);
  1820. }
  1821. return {
  1822. min: min,
  1823. max: max
  1824. };
  1825. }
  1826. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  1827. if (!this._selectionOctree) {
  1828. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  1829. }
  1830. var worldExtends = this.getWorldExtends();
  1831. // Update octree
  1832. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  1833. return this._selectionOctree;
  1834. }
  1835. // Picking
  1836. public createPickingRay(x: number, y: number, world: Matrix, camera: Camera, cameraViewSpace = false): Ray {
  1837. var engine = this._engine;
  1838. if (!camera) {
  1839. if (!this.activeCamera)
  1840. throw new Error("Active camera not set");
  1841. camera = this.activeCamera;
  1842. }
  1843. var cameraViewport = camera.viewport;
  1844. var viewport = cameraViewport.toGlobal(engine);
  1845. // Moving coordinates to local viewport world
  1846. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  1847. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  1848. return Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  1849. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  1850. }
  1851. public createPickingRayInCameraSpace(x: number, y: number, camera: Camera): Ray {
  1852. var engine = this._engine;
  1853. if (!camera) {
  1854. if (!this.activeCamera)
  1855. throw new Error("Active camera not set");
  1856. camera = this.activeCamera;
  1857. }
  1858. var cameraViewport = camera.viewport;
  1859. var viewport = cameraViewport.toGlobal(engine);
  1860. var identity = Matrix.Identity();
  1861. // Moving coordinates to local viewport world
  1862. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  1863. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  1864. return Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  1865. }
  1866. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): PickingInfo {
  1867. var pickingInfo = null;
  1868. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  1869. var mesh = this.meshes[meshIndex];
  1870. if (predicate) {
  1871. if (!predicate(mesh)) {
  1872. continue;
  1873. }
  1874. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  1875. continue;
  1876. }
  1877. var world = mesh.getWorldMatrix();
  1878. var ray = rayFunction(world);
  1879. var result = mesh.intersects(ray, fastCheck);
  1880. if (!result || !result.hit)
  1881. continue;
  1882. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  1883. continue;
  1884. pickingInfo = result;
  1885. if (fastCheck) {
  1886. break;
  1887. }
  1888. }
  1889. return pickingInfo || new PickingInfo();
  1890. }
  1891. private _internalPickSprites(ray: Ray, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  1892. var pickingInfo = null;
  1893. camera = camera || this.activeCamera;
  1894. if (this.spriteManagers.length > 0) {
  1895. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  1896. var spriteManager = this.spriteManagers[spriteIndex];
  1897. if (!spriteManager.isPickable) {
  1898. continue;
  1899. }
  1900. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  1901. if (!result || !result.hit)
  1902. continue;
  1903. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  1904. continue;
  1905. pickingInfo = result;
  1906. if (fastCheck) {
  1907. break;
  1908. }
  1909. }
  1910. }
  1911. return pickingInfo || new PickingInfo();
  1912. }
  1913. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  1914. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  1915. /// <param name="x">X position on screen</param>
  1916. /// <param name="y">Y position on screen</param>
  1917. /// <param name="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</param>
  1918. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  1919. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  1920. return this._internalPick(world => this.createPickingRay(x, y, world, camera), predicate, fastCheck);
  1921. }
  1922. public pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  1923. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  1924. /// <param name="x">X position on screen</param>
  1925. /// <param name="y">Y position on screen</param>
  1926. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  1927. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  1928. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  1929. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  1930. }
  1931. public pickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean, fastCheck?: boolean) {
  1932. return this._internalPick(world => {
  1933. if (!this._pickWithRayInverseMatrix) {
  1934. this._pickWithRayInverseMatrix = Matrix.Identity();
  1935. }
  1936. world.invertToRef(this._pickWithRayInverseMatrix);
  1937. return Ray.Transform(ray, this._pickWithRayInverseMatrix);
  1938. }, predicate, fastCheck);
  1939. }
  1940. public setPointerOverMesh(mesh: AbstractMesh): void {
  1941. if (this._pointerOverMesh === mesh) {
  1942. return;
  1943. }
  1944. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1945. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  1946. }
  1947. this._pointerOverMesh = mesh;
  1948. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1949. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  1950. }
  1951. }
  1952. public getPointerOverMesh(): AbstractMesh {
  1953. return this._pointerOverMesh;
  1954. }
  1955. // Physics
  1956. public getPhysicsEngine(): PhysicsEngine {
  1957. return this._physicsEngine;
  1958. }
  1959. /**
  1960. * Enables physics to the current scene
  1961. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  1962. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  1963. * @return {boolean} was the physics engine initialized
  1964. */
  1965. public enablePhysics(gravity?: Vector3, plugin?: IPhysicsEnginePlugin): boolean {
  1966. if (this._physicsEngine) {
  1967. return true;
  1968. }
  1969. this._physicsEngine = new PhysicsEngine(plugin);
  1970. if (!this._physicsEngine.isSupported()) {
  1971. this._physicsEngine = null;
  1972. return false;
  1973. }
  1974. this._physicsEngine._initialize(gravity);
  1975. return true;
  1976. }
  1977. public disablePhysicsEngine(): void {
  1978. if (!this._physicsEngine) {
  1979. return;
  1980. }
  1981. this._physicsEngine.dispose();
  1982. this._physicsEngine = undefined;
  1983. }
  1984. public isPhysicsEnabled(): boolean {
  1985. return this._physicsEngine !== undefined;
  1986. }
  1987. /**
  1988. * Sets the gravity of the physics engine (and NOT of the scene)
  1989. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  1990. */
  1991. public setGravity(gravity: Vector3): void {
  1992. if (!this._physicsEngine) {
  1993. return;
  1994. }
  1995. this._physicsEngine._setGravity(gravity);
  1996. }
  1997. public createCompoundImpostor(parts: any, options: PhysicsBodyCreationOptions): any {
  1998. if (parts.parts) { // Old API
  1999. options = parts;
  2000. parts = parts.parts;
  2001. }
  2002. if (!this._physicsEngine) {
  2003. return null;
  2004. }
  2005. for (var index = 0; index < parts.length; index++) {
  2006. var mesh = parts[index].mesh;
  2007. mesh._physicImpostor = parts[index].impostor;
  2008. mesh._physicsMass = options.mass / parts.length;
  2009. mesh._physicsFriction = options.friction;
  2010. mesh._physicRestitution = options.restitution;
  2011. }
  2012. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  2013. }
  2014. public deleteCompoundImpostor(compound: any): void {
  2015. for (var index = 0; index < compound.parts.length; index++) {
  2016. var mesh = compound.parts[index].mesh;
  2017. mesh._physicImpostor = PhysicsEngine.NoImpostor;
  2018. this._physicsEngine._unregisterMesh(mesh);
  2019. }
  2020. }
  2021. // Misc.
  2022. public createDefaultCameraOrLight() {
  2023. // Light
  2024. if (this.lights.length === 0) {
  2025. new HemisphericLight("default light", Vector3.Up(), this);
  2026. }
  2027. // Camera
  2028. if (!this.activeCamera) {
  2029. var camera = new FreeCamera("default camera", Vector3.Zero(), this);
  2030. // Compute position
  2031. var worldExtends = this.getWorldExtends();
  2032. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  2033. camera.position = new Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  2034. camera.setTarget(worldCenter);
  2035. this.activeCamera = camera;
  2036. }
  2037. }
  2038. // Tags
  2039. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  2040. if (tagsQuery === undefined) {
  2041. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  2042. return list;
  2043. }
  2044. var listByTags = [];
  2045. forEach = forEach || ((item: any) => { return; });
  2046. for (var i in list) {
  2047. var item = list[i];
  2048. if (Tags.MatchesQuery(item, tagsQuery)) {
  2049. listByTags.push(item);
  2050. forEach(item);
  2051. }
  2052. }
  2053. return listByTags;
  2054. }
  2055. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  2056. return this._getByTags(this.meshes, tagsQuery, forEach);
  2057. }
  2058. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  2059. return this._getByTags(this.cameras, tagsQuery, forEach);
  2060. }
  2061. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  2062. return this._getByTags(this.lights, tagsQuery, forEach);
  2063. }
  2064. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  2065. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  2066. }
  2067. }
  2068. }