babylon.scene.ts 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  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. // Pointers
  56. private _onPointerMove: (evt: PointerEvent) => void;
  57. private _onPointerDown: (evt: PointerEvent) => void;
  58. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  59. 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
  60. private _pointerX: number;
  61. private _pointerY: number;
  62. private _meshUnderPointer: AbstractMesh;
  63. // Keyboard
  64. private _onKeyDown: (evt: Event) => void;
  65. private _onKeyUp: (evt: Event) => void;
  66. // Fog
  67. /**
  68. * is fog enabled on this scene.
  69. * @type {boolean}
  70. */
  71. public fogEnabled = true;
  72. public fogMode = Scene.FOGMODE_NONE;
  73. public fogColor = new Color3(0.2, 0.2, 0.3);
  74. public fogDensity = 0.1;
  75. public fogStart = 0;
  76. public fogEnd = 1000.0;
  77. // Lights
  78. /**
  79. * is shadow enabled on this scene.
  80. * @type {boolean}
  81. */
  82. public shadowsEnabled = true;
  83. /**
  84. * is light enabled on this scene.
  85. * @type {boolean}
  86. */
  87. public lightsEnabled = true;
  88. /**
  89. * All of the lights added to this scene.
  90. * @see BABYLON.Light
  91. * @type {BABYLON.Light[]}
  92. */
  93. public lights = new Array<Light>();
  94. // Cameras
  95. /**
  96. * All of the cameras added to this scene.
  97. * @see BABYLON.Camera
  98. * @type {BABYLON.Camera[]}
  99. */
  100. public cameras = new Array<Camera>();
  101. public activeCameras = new Array<Camera>();
  102. public activeCamera: Camera;
  103. // Meshes
  104. /**
  105. * All of the (abstract) meshes added to this scene.
  106. * @see BABYLON.AbstractMesh
  107. * @type {BABYLON.AbstractMesh[]}
  108. */
  109. public meshes = new Array<AbstractMesh>();
  110. // Geometries
  111. private _geometries = new Array<Geometry>();
  112. public materials = new Array<Material>();
  113. public multiMaterials = new Array<MultiMaterial>();
  114. public defaultMaterial = new StandardMaterial("default material", this);
  115. // Textures
  116. public texturesEnabled = true;
  117. public textures = new Array<BaseTexture>();
  118. // Particles
  119. public particlesEnabled = true;
  120. public particleSystems = new Array<ParticleSystem>();
  121. // Sprites
  122. public spriteManagers = new Array<SpriteManager>();
  123. // Layers
  124. public layers = new Array<Layer>();
  125. // Skeletons
  126. public skeletonsEnabled = true;
  127. public skeletons = new Array<Skeleton>();
  128. // Lens flares
  129. public lensFlaresEnabled = true;
  130. public lensFlareSystems = new Array<LensFlareSystem>();
  131. // Collisions
  132. public collisionsEnabled = true;
  133. public gravity = new Vector3(0, -9.0, 0);
  134. // Postprocesses
  135. public postProcessesEnabled = true;
  136. public postProcessManager: PostProcessManager;
  137. public postProcessRenderPipelineManager: PostProcessRenderPipelineManager;
  138. // Customs render targets
  139. public renderTargetsEnabled = true;
  140. public customRenderTargets = new Array<RenderTargetTexture>();
  141. // Delay loading
  142. public useDelayedTextureLoading: boolean;
  143. // Imported meshes
  144. public importedMeshesFiles = new Array<String>();
  145. // Database
  146. public database; //ANY
  147. // Actions
  148. /**
  149. * This scene's action manager
  150. * @type {BABYLON.ActionManager}
  151. */
  152. public actionManager: ActionManager;
  153. public _actionManagers = new Array<ActionManager>();
  154. private _meshesForIntersections = new SmartArray<AbstractMesh>(256);
  155. // Procedural textures
  156. public proceduralTexturesEnabled = true;
  157. public _proceduralTextures = new Array<ProceduralTexture>();
  158. // Sound Tracks
  159. public mainSoundTrack: SoundTrack;
  160. public soundTracks = new Array<SoundTrack>();
  161. // Private
  162. private _engine: Engine;
  163. private _totalVertices = 0;
  164. public _activeVertices = 0;
  165. public _activeParticles = 0;
  166. private _lastFrameDuration = 0;
  167. private _evaluateActiveMeshesDuration = 0;
  168. private _renderTargetsDuration = 0;
  169. public _particlesDuration = 0;
  170. private _renderDuration = 0;
  171. public _spritesDuration = 0;
  172. private _animationRatio = 0;
  173. private _animationStartDate: number;
  174. public _cachedMaterial: Material;
  175. private _renderId = 0;
  176. private _executeWhenReadyTimeoutId = -1;
  177. public _toBeDisposed = new SmartArray<IDisposable>(256);
  178. private _onReadyCallbacks = new Array<() => void>();
  179. private _pendingData = [];//ANY
  180. private _onBeforeRenderCallbacks = new Array<() => void>();
  181. private _onAfterRenderCallbacks = new Array<() => void>();
  182. private _activeMeshes = new SmartArray<Mesh>(256);
  183. private _processedMaterials = new SmartArray<Material>(256);
  184. private _renderTargets = new SmartArray<RenderTargetTexture>(256);
  185. public _activeParticleSystems = new SmartArray<ParticleSystem>(256);
  186. private _activeSkeletons = new SmartArray<Skeleton>(32);
  187. private _activeBones = 0;
  188. private _renderingManager: RenderingManager;
  189. private _physicsEngine: PhysicsEngine;
  190. public _activeAnimatables = new Array<Animatable>();
  191. private _transformMatrix = Matrix.Zero();
  192. private _pickWithRayInverseMatrix: Matrix;
  193. private _scaledPosition = Vector3.Zero();
  194. private _scaledVelocity = Vector3.Zero();
  195. private _boundingBoxRenderer: BoundingBoxRenderer;
  196. private _outlineRenderer: OutlineRenderer;
  197. private _viewMatrix: Matrix;
  198. private _projectionMatrix: Matrix;
  199. private _frustumPlanes: Plane[];
  200. private _selectionOctree: Octree<AbstractMesh>;
  201. private _pointerOverMesh: AbstractMesh;
  202. private _debugLayer: DebugLayer;
  203. private _depthRenderer: DepthRenderer;
  204. /**
  205. * @constructor
  206. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  207. */
  208. constructor(engine: Engine) {
  209. this._engine = engine;
  210. engine.scenes.push(this);
  211. this._renderingManager = new RenderingManager(this);
  212. this.postProcessManager = new PostProcessManager(this);
  213. this.postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  214. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  215. this._outlineRenderer = new OutlineRenderer(this);
  216. this.attachControl();
  217. this._debugLayer = new DebugLayer(this);
  218. this.mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  219. }
  220. // Properties
  221. public get debugLayer(): DebugLayer {
  222. return this._debugLayer;
  223. }
  224. /**
  225. * The mesh that is currently under the pointer.
  226. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  227. */
  228. public get meshUnderPointer(): AbstractMesh {
  229. return this._meshUnderPointer;
  230. }
  231. /**
  232. * Current on-screen X position of the pointer
  233. * @return {number} X position of the pointer
  234. */
  235. public get pointerX(): number {
  236. return this._pointerX;
  237. }
  238. /**
  239. * Current on-screen Y position of the pointer
  240. * @return {number} Y position of the pointer
  241. */
  242. public get pointerY(): number {
  243. return this._pointerY;
  244. }
  245. public getCachedMaterial(): Material {
  246. return this._cachedMaterial;
  247. }
  248. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  249. return this._boundingBoxRenderer;
  250. }
  251. public getOutlineRenderer(): OutlineRenderer {
  252. return this._outlineRenderer;
  253. }
  254. public getEngine(): Engine {
  255. return this._engine;
  256. }
  257. public getTotalVertices(): number {
  258. return this._totalVertices;
  259. }
  260. public getActiveVertices(): number {
  261. return this._activeVertices;
  262. }
  263. public getActiveParticles(): number {
  264. return this._activeParticles;
  265. }
  266. public getActiveBones(): number {
  267. return this._activeBones;
  268. }
  269. // Stats
  270. public getLastFrameDuration(): number {
  271. return this._lastFrameDuration;
  272. }
  273. public getEvaluateActiveMeshesDuration(): number {
  274. return this._evaluateActiveMeshesDuration;
  275. }
  276. public getActiveMeshes(): SmartArray<Mesh> {
  277. return this._activeMeshes;
  278. }
  279. public getRenderTargetsDuration(): number {
  280. return this._renderTargetsDuration;
  281. }
  282. public getRenderDuration(): number {
  283. return this._renderDuration;
  284. }
  285. public getParticlesDuration(): number {
  286. return this._particlesDuration;
  287. }
  288. public getSpritesDuration(): number {
  289. return this._spritesDuration;
  290. }
  291. public getAnimationRatio(): number {
  292. return this._animationRatio;
  293. }
  294. public getRenderId(): number {
  295. return this._renderId;
  296. }
  297. public incrementRenderId(): void {
  298. this._renderId++;
  299. }
  300. private _updatePointerPosition(evt: PointerEvent): void {
  301. var canvasRect = this._engine.getRenderingCanvasClientRect();
  302. this._pointerX = evt.clientX - canvasRect.left;
  303. this._pointerY = evt.clientY - canvasRect.top;
  304. if (this.cameraToUseForPointers) {
  305. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  306. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  307. }
  308. }
  309. // Pointers handling
  310. public attachControl() {
  311. this._onPointerMove = (evt: PointerEvent) => {
  312. var canvas = this._engine.getRenderingCanvas();
  313. this._updatePointerPosition(evt);
  314. var pickResult = this.pick(this._pointerX, this._pointerY,
  315. (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers,
  316. false,
  317. this.cameraToUseForPointers);
  318. if (pickResult.hit) {
  319. this._meshUnderPointer = pickResult.pickedMesh;
  320. this.setPointerOverMesh(pickResult.pickedMesh);
  321. canvas.style.cursor = "pointer";
  322. } else {
  323. this.setPointerOverMesh(null);
  324. canvas.style.cursor = "";
  325. this._meshUnderPointer = null;
  326. }
  327. };
  328. this._onPointerDown = (evt: PointerEvent) => {
  329. var predicate = null;
  330. if (!this.onPointerDown) {
  331. predicate = (mesh: AbstractMesh): boolean => {
  332. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  333. };
  334. }
  335. this._updatePointerPosition(evt);
  336. var pickResult = this.pick(this._pointerX, this._pointerY, predicate, false, this.cameraToUseForPointers);
  337. if (pickResult.hit) {
  338. if (pickResult.pickedMesh.actionManager) {
  339. switch (evt.button) {
  340. case 0:
  341. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  342. break;
  343. case 1:
  344. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  345. break;
  346. case 2:
  347. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  348. break;
  349. }
  350. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  351. }
  352. }
  353. if (this.onPointerDown) {
  354. this.onPointerDown(evt, pickResult);
  355. }
  356. };
  357. this._onKeyDown = (evt: Event) => {
  358. if (this.actionManager) {
  359. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  360. }
  361. };
  362. this._onKeyUp = (evt: Event) => {
  363. if (this.actionManager) {
  364. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  365. }
  366. };
  367. var eventPrefix = Tools.GetPointerPrefix();
  368. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  369. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  370. Tools.RegisterTopRootEvents([
  371. { name: "keydown", handler: this._onKeyDown },
  372. { name: "keyup", handler: this._onKeyUp }
  373. ]);
  374. }
  375. public detachControl() {
  376. var eventPrefix = Tools.GetPointerPrefix();
  377. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  378. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  379. Tools.UnregisterTopRootEvents([
  380. { name: "keydown", handler: this._onKeyDown },
  381. { name: "keyup", handler: this._onKeyUp }
  382. ]);
  383. }
  384. // Ready
  385. public isReady(): boolean {
  386. if (this._pendingData.length > 0) {
  387. return false;
  388. }
  389. for (var index = 0; index < this._geometries.length; index++) {
  390. var geometry = this._geometries[index];
  391. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  392. return false;
  393. }
  394. }
  395. for (index = 0; index < this.meshes.length; index++) {
  396. var mesh = this.meshes[index];
  397. if (!mesh.isReady()) {
  398. return false;
  399. }
  400. var mat = mesh.material;
  401. if (mat) {
  402. if (!mat.isReady(mesh)) {
  403. return false;
  404. }
  405. }
  406. }
  407. return true;
  408. }
  409. public resetCachedMaterial(): void {
  410. this._cachedMaterial = null;
  411. }
  412. public registerBeforeRender(func: () => void): void {
  413. this._onBeforeRenderCallbacks.push(func);
  414. }
  415. public unregisterBeforeRender(func: () => void): void {
  416. var index = this._onBeforeRenderCallbacks.indexOf(func);
  417. if (index > -1) {
  418. this._onBeforeRenderCallbacks.splice(index, 1);
  419. }
  420. }
  421. public registerAfterRender(func: () => void): void {
  422. this._onAfterRenderCallbacks.push(func);
  423. }
  424. public unregisterAfterRender(func: () => void): void {
  425. var index = this._onAfterRenderCallbacks.indexOf(func);
  426. if (index > -1) {
  427. this._onAfterRenderCallbacks.splice(index, 1);
  428. }
  429. }
  430. public _addPendingData(data): void {
  431. this._pendingData.push(data);
  432. }
  433. public _removePendingData(data): void {
  434. var index = this._pendingData.indexOf(data);
  435. if (index !== -1) {
  436. this._pendingData.splice(index, 1);
  437. }
  438. }
  439. public getWaitingItemsCount(): number {
  440. return this._pendingData.length;
  441. }
  442. /**
  443. * Registers a function to be executed when the scene is ready.
  444. * @param {Function} func - the function to be executed.
  445. */
  446. public executeWhenReady(func: () => void): void {
  447. this._onReadyCallbacks.push(func);
  448. if (this._executeWhenReadyTimeoutId !== -1) {
  449. return;
  450. }
  451. this._executeWhenReadyTimeoutId = setTimeout(() => {
  452. this._checkIsReady();
  453. }, 150);
  454. }
  455. public _checkIsReady() {
  456. if (this.isReady()) {
  457. this._onReadyCallbacks.forEach(func => {
  458. func();
  459. });
  460. this._onReadyCallbacks = [];
  461. this._executeWhenReadyTimeoutId = -1;
  462. return;
  463. }
  464. this._executeWhenReadyTimeoutId = setTimeout(() => {
  465. this._checkIsReady();
  466. }, 150);
  467. }
  468. // Animations
  469. /**
  470. * Will start the animation sequence of a given target
  471. * @param target - the target
  472. * @param {number} from - from which frame should animation start
  473. * @param {number} to - till which frame should animation run.
  474. * @param {boolean} [loop] - should the animation loop
  475. * @param {number} [speedRatio] - the speed in which to run the animation
  476. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  477. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  478. * @return {BABYLON.Animatable} the animatable object created for this animation
  479. * @see BABYLON.Animatable
  480. * @see http://doc.babylonjs.com/page.php?p=22081
  481. */
  482. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  483. if (speedRatio === undefined) {
  484. speedRatio = 1.0;
  485. }
  486. this.stopAnimation(target);
  487. if (!animatable) {
  488. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  489. }
  490. // Local animations
  491. if (target.animations) {
  492. animatable.appendAnimations(target, target.animations);
  493. }
  494. // Children animations
  495. if (target.getAnimatables) {
  496. var animatables = target.getAnimatables();
  497. for (var index = 0; index < animatables.length; index++) {
  498. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  499. }
  500. }
  501. return animatable;
  502. }
  503. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  504. if (speedRatio === undefined) {
  505. speedRatio = 1.0;
  506. }
  507. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  508. return animatable;
  509. }
  510. public getAnimatableByTarget(target: any): Animatable {
  511. for (var index = 0; index < this._activeAnimatables.length; index++) {
  512. if (this._activeAnimatables[index].target === target) {
  513. return this._activeAnimatables[index];
  514. }
  515. }
  516. return null;
  517. }
  518. /**
  519. * Will stop the animation of the given target
  520. * @param target - the target
  521. * @see beginAnimation
  522. */
  523. public stopAnimation(target: any): void {
  524. var animatable = this.getAnimatableByTarget(target);
  525. if (animatable) {
  526. animatable.stop();
  527. }
  528. }
  529. private _animate(): void {
  530. if (!this.animationsEnabled) {
  531. return;
  532. }
  533. if (!this._animationStartDate) {
  534. this._animationStartDate = Tools.Now;
  535. }
  536. // Getting time
  537. var now = Tools.Now;
  538. var delay = now - this._animationStartDate;
  539. for (var index = 0; index < this._activeAnimatables.length; index++) {
  540. if (!this._activeAnimatables[index]._animate(delay)) {
  541. this._activeAnimatables.splice(index, 1);
  542. index--;
  543. }
  544. }
  545. }
  546. // Matrix
  547. public getViewMatrix(): Matrix {
  548. return this._viewMatrix;
  549. }
  550. public getProjectionMatrix(): Matrix {
  551. return this._projectionMatrix;
  552. }
  553. public getTransformMatrix(): Matrix {
  554. return this._transformMatrix;
  555. }
  556. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  557. this._viewMatrix = view;
  558. this._projectionMatrix = projection;
  559. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  560. }
  561. // Methods
  562. /**
  563. * sets the active camera of the scene using its ID
  564. * @param {string} id - the camera's ID
  565. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  566. * @see activeCamera
  567. */
  568. public setActiveCameraByID(id: string): Camera {
  569. var camera = this.getCameraByID(id);
  570. if (camera) {
  571. this.activeCamera = camera;
  572. return camera;
  573. }
  574. return null;
  575. }
  576. /**
  577. * sets the active camera of the scene using its name
  578. * @param {string} name - the camera's name
  579. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  580. * @see activeCamera
  581. */
  582. public setActiveCameraByName(name: string): Camera {
  583. var camera = this.getCameraByName(name);
  584. if (camera) {
  585. this.activeCamera = camera;
  586. return camera;
  587. }
  588. return null;
  589. }
  590. /**
  591. * get a material using its id
  592. * @param {string} the material's ID
  593. * @return {BABYLON.Material|null} the material or null if none found.
  594. */
  595. public getMaterialByID(id: string): Material {
  596. for (var index = 0; index < this.materials.length; index++) {
  597. if (this.materials[index].id === id) {
  598. return this.materials[index];
  599. }
  600. }
  601. return null;
  602. }
  603. /**
  604. * get a material using its name
  605. * @param {string} the material's name
  606. * @return {BABYLON.Material|null} the material or null if none found.
  607. */
  608. public getMaterialByName(name: string): Material {
  609. for (var index = 0; index < this.materials.length; index++) {
  610. if (this.materials[index].name === name) {
  611. return this.materials[index];
  612. }
  613. }
  614. return null;
  615. }
  616. public getCameraByID(id: string): Camera {
  617. for (var index = 0; index < this.cameras.length; index++) {
  618. if (this.cameras[index].id === id) {
  619. return this.cameras[index];
  620. }
  621. }
  622. return null;
  623. }
  624. /**
  625. * get a camera using its name
  626. * @param {string} the camera's name
  627. * @return {BABYLON.Camera|null} the camera or null if none found.
  628. */
  629. public getCameraByName(name: string): Camera {
  630. for (var index = 0; index < this.cameras.length; index++) {
  631. if (this.cameras[index].name === name) {
  632. return this.cameras[index];
  633. }
  634. }
  635. return null;
  636. }
  637. /**
  638. * get a light node using its name
  639. * @param {string} the light's name
  640. * @return {BABYLON.Light|null} the light or null if none found.
  641. */
  642. public getLightByName(name: string): Light {
  643. for (var index = 0; index < this.lights.length; index++) {
  644. if (this.lights[index].name === name) {
  645. return this.lights[index];
  646. }
  647. }
  648. return null;
  649. }
  650. /**
  651. * get a light node using its ID
  652. * @param {string} the light's id
  653. * @return {BABYLON.Light|null} the light or null if none found.
  654. */
  655. public getLightByID(id: string): Light {
  656. for (var index = 0; index < this.lights.length; index++) {
  657. if (this.lights[index].id === id) {
  658. return this.lights[index];
  659. }
  660. }
  661. return null;
  662. }
  663. /**
  664. * get a geometry using its ID
  665. * @param {string} the geometry's id
  666. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  667. */
  668. public getGeometryByID(id: string): Geometry {
  669. for (var index = 0; index < this._geometries.length; index++) {
  670. if (this._geometries[index].id === id) {
  671. return this._geometries[index];
  672. }
  673. }
  674. return null;
  675. }
  676. /**
  677. * add a new geometry to this scene.
  678. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  679. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  680. * @return {boolean} was the geometry added or not
  681. */
  682. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  683. if (!force && this.getGeometryByID(geometry.id)) {
  684. return false;
  685. }
  686. this._geometries.push(geometry);
  687. return true;
  688. }
  689. public getGeometries(): Geometry[] {
  690. return this._geometries;
  691. }
  692. /**
  693. * Get a the first added mesh found of a given ID
  694. * @param {string} id - the id to search for
  695. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  696. */
  697. public getMeshByID(id: string): AbstractMesh {
  698. for (var index = 0; index < this.meshes.length; index++) {
  699. if (this.meshes[index].id === id) {
  700. return this.meshes[index];
  701. }
  702. }
  703. return null;
  704. }
  705. /**
  706. * Get a the last added mesh found of a given ID
  707. * @param {string} id - the id to search for
  708. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  709. */
  710. public getLastMeshByID(id: string): AbstractMesh {
  711. for (var index = this.meshes.length - 1; index >= 0; index--) {
  712. if (this.meshes[index].id === id) {
  713. return this.meshes[index];
  714. }
  715. }
  716. return null;
  717. }
  718. /**
  719. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  720. * @param {string} id - the id to search for
  721. * @return {BABYLON.Node|null} the node found or null if not found at all.
  722. */
  723. public getLastEntryByID(id: string): Node {
  724. for (var index = this.meshes.length - 1; index >= 0; index--) {
  725. if (this.meshes[index].id === id) {
  726. return this.meshes[index];
  727. }
  728. }
  729. for (index = this.cameras.length - 1; index >= 0; index--) {
  730. if (this.cameras[index].id === id) {
  731. return this.cameras[index];
  732. }
  733. }
  734. for (index = this.lights.length - 1; index >= 0; index--) {
  735. if (this.lights[index].id === id) {
  736. return this.lights[index];
  737. }
  738. }
  739. return null;
  740. }
  741. public getNodeByName(name: string): Node {
  742. var mesh = this.getMeshByName(name);
  743. if (mesh) {
  744. return mesh;
  745. }
  746. var light = this.getLightByName(name);
  747. if (light) {
  748. return light;
  749. }
  750. return this.getCameraByName(name);
  751. }
  752. public getMeshByName(name: string): AbstractMesh {
  753. for (var index = 0; index < this.meshes.length; index++) {
  754. if (this.meshes[index].name === name) {
  755. return this.meshes[index];
  756. }
  757. }
  758. return null;
  759. }
  760. public getSoundByName(name: string): Sound {
  761. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  762. if (this.mainSoundTrack.soundCollection[index].name === name) {
  763. return this.mainSoundTrack.soundCollection[index];
  764. }
  765. }
  766. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  767. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  768. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  769. return this.soundTracks[sdIndex].soundCollection[index];
  770. }
  771. }
  772. }
  773. return null;
  774. }
  775. public getLastSkeletonByID(id: string): Skeleton {
  776. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  777. if (this.skeletons[index].id === id) {
  778. return this.skeletons[index];
  779. }
  780. }
  781. return null;
  782. }
  783. public getSkeletonById(id: string): Skeleton {
  784. for (var index = 0; index < this.skeletons.length; index++) {
  785. if (this.skeletons[index].id === id) {
  786. return this.skeletons[index];
  787. }
  788. }
  789. return null;
  790. }
  791. public getSkeletonByName(name: string): Skeleton {
  792. for (var index = 0; index < this.skeletons.length; index++) {
  793. if (this.skeletons[index].name === name) {
  794. return this.skeletons[index];
  795. }
  796. }
  797. return null;
  798. }
  799. public isActiveMesh(mesh: Mesh): boolean {
  800. return (this._activeMeshes.indexOf(mesh) !== -1);
  801. }
  802. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  803. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  804. var material = subMesh.getMaterial();
  805. if (mesh.showSubMeshesBoundingBox) {
  806. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  807. }
  808. if (material) {
  809. // Render targets
  810. if (material.getRenderTargetTextures) {
  811. if (this._processedMaterials.indexOf(material) === -1) {
  812. this._processedMaterials.push(material);
  813. this._renderTargets.concat(material.getRenderTargetTextures());
  814. }
  815. }
  816. // Dispatch
  817. this._activeVertices += subMesh.indexCount;
  818. this._renderingManager.dispatch(subMesh);
  819. }
  820. }
  821. }
  822. private _evaluateActiveMeshes(): void {
  823. this._activeMeshes.reset();
  824. this._renderingManager.reset();
  825. this._processedMaterials.reset();
  826. this._activeParticleSystems.reset();
  827. this._activeSkeletons.reset();
  828. this._boundingBoxRenderer.reset();
  829. if (!this._frustumPlanes) {
  830. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  831. } else {
  832. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  833. }
  834. // Meshes
  835. var meshes: AbstractMesh[];
  836. var len: number;
  837. if (this._selectionOctree) { // Octree
  838. var selection = this._selectionOctree.select(this._frustumPlanes);
  839. meshes = selection.data;
  840. len = selection.length;
  841. } else { // Full scene traversal
  842. len = this.meshes.length;
  843. meshes = this.meshes;
  844. }
  845. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  846. var mesh = meshes[meshIndex];
  847. if (mesh.isBlocked) {
  848. continue;
  849. }
  850. this._totalVertices += mesh.getTotalVertices();
  851. if (!mesh.isReady()) {
  852. continue;
  853. }
  854. mesh.computeWorldMatrix();
  855. // Intersections
  856. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  857. this._meshesForIntersections.pushNoDuplicate(mesh);
  858. }
  859. // Switch to current LOD
  860. var meshLOD = mesh.getLOD(this.activeCamera);
  861. if (!meshLOD) {
  862. continue;
  863. }
  864. mesh._preActivate();
  865. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  866. this._activeMeshes.push(mesh);
  867. mesh._activate(this._renderId);
  868. this._activeMesh(meshLOD);
  869. }
  870. }
  871. // Particle systems
  872. var beforeParticlesDate = Tools.Now;
  873. if (this.particlesEnabled) {
  874. Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  875. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  876. var particleSystem = this.particleSystems[particleIndex];
  877. if (!particleSystem.isStarted()) {
  878. continue;
  879. }
  880. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  881. this._activeParticleSystems.push(particleSystem);
  882. particleSystem.animate();
  883. }
  884. }
  885. Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  886. }
  887. this._particlesDuration += Tools.Now - beforeParticlesDate;
  888. }
  889. private _activeMesh(mesh: AbstractMesh): void {
  890. if (mesh.skeleton && this.skeletonsEnabled) {
  891. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  892. }
  893. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  894. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  895. }
  896. if (mesh && mesh.subMeshes) {
  897. // Submeshes Octrees
  898. var len: number;
  899. var subMeshes: SubMesh[];
  900. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  901. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  902. len = intersections.length;
  903. subMeshes = intersections.data;
  904. } else {
  905. subMeshes = mesh.subMeshes;
  906. len = subMeshes.length;
  907. }
  908. for (var subIndex = 0; subIndex < len; subIndex++) {
  909. var subMesh = subMeshes[subIndex];
  910. this._evaluateSubMesh(subMesh, mesh);
  911. }
  912. }
  913. }
  914. public updateTransformMatrix(force?: boolean): void {
  915. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  916. }
  917. private _renderForCamera(camera: Camera): void {
  918. var engine = this._engine;
  919. this.activeCamera = camera;
  920. if (!this.activeCamera)
  921. throw new Error("Active camera not set");
  922. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  923. // Viewport
  924. engine.setViewport(this.activeCamera.viewport);
  925. // Camera
  926. this._renderId++;
  927. this.updateTransformMatrix();
  928. if (this.beforeCameraRender) {
  929. this.beforeCameraRender(this.activeCamera);
  930. }
  931. // Meshes
  932. var beforeEvaluateActiveMeshesDate = Tools.Now;
  933. Tools.StartPerformanceCounter("Active meshes evaluation");
  934. this._evaluateActiveMeshes();
  935. this._evaluateActiveMeshesDuration += Tools.Now - beforeEvaluateActiveMeshesDate;
  936. Tools.EndPerformanceCounter("Active meshes evaluation");
  937. // Skeletons
  938. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  939. var skeleton = this._activeSkeletons.data[skeletonIndex];
  940. skeleton.prepare();
  941. this._activeBones += skeleton.bones.length;
  942. }
  943. // Render targets
  944. var beforeRenderTargetDate = Tools.Now;
  945. if (this.renderTargetsEnabled) {
  946. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  947. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  948. var renderTarget = this._renderTargets.data[renderIndex];
  949. if (renderTarget._shouldRender()) {
  950. this._renderId++;
  951. renderTarget.render();
  952. }
  953. }
  954. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  955. this._renderId++;
  956. }
  957. if (this._renderTargets.length > 0) { // Restore back buffer
  958. engine.restoreDefaultFramebuffer();
  959. }
  960. this._renderTargetsDuration += Tools.Now - beforeRenderTargetDate;
  961. // Prepare Frame
  962. this.postProcessManager._prepareFrame();
  963. var beforeRenderDate = Tools.Now;
  964. // Backgrounds
  965. if (this.layers.length) {
  966. engine.setDepthBuffer(false);
  967. var layerIndex;
  968. var layer;
  969. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  970. layer = this.layers[layerIndex];
  971. if (layer.isBackground) {
  972. layer.render();
  973. }
  974. }
  975. engine.setDepthBuffer(true);
  976. }
  977. // Render
  978. Tools.StartPerformanceCounter("Main render");
  979. this._renderingManager.render(null, null, true, true);
  980. Tools.EndPerformanceCounter("Main render");
  981. // Bounding boxes
  982. this._boundingBoxRenderer.render();
  983. // Lens flares
  984. if (this.lensFlaresEnabled) {
  985. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  986. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  987. this.lensFlareSystems[lensFlareSystemIndex].render();
  988. }
  989. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  990. }
  991. // Foregrounds
  992. if (this.layers.length) {
  993. engine.setDepthBuffer(false);
  994. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  995. layer = this.layers[layerIndex];
  996. if (!layer.isBackground) {
  997. layer.render();
  998. }
  999. }
  1000. engine.setDepthBuffer(true);
  1001. }
  1002. this._renderDuration += Tools.Now - beforeRenderDate;
  1003. // Finalize frame
  1004. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  1005. // Update camera
  1006. this.activeCamera._updateFromScene();
  1007. // Reset some special arrays
  1008. this._renderTargets.reset();
  1009. if (this.afterCameraRender) {
  1010. this.afterCameraRender(this.activeCamera);
  1011. }
  1012. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  1013. }
  1014. private _processSubCameras(camera: Camera): void {
  1015. if (camera.subCameras.length === 0) {
  1016. this._renderForCamera(camera);
  1017. return;
  1018. }
  1019. // Sub-cameras
  1020. for (var index = 0; index < camera.subCameras.length; index++) {
  1021. this._renderForCamera(camera.subCameras[index]);
  1022. }
  1023. this.activeCamera = camera;
  1024. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  1025. // Update camera
  1026. this.activeCamera._updateFromScene();
  1027. }
  1028. private _checkIntersections(): void {
  1029. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  1030. var sourceMesh = this._meshesForIntersections.data[index];
  1031. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  1032. var action = sourceMesh.actionManager.actions[actionIndex];
  1033. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1034. var parameters = action.getTriggerParameter();
  1035. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  1036. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  1037. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  1038. if (areIntersecting && currentIntersectionInProgress === -1) {
  1039. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  1040. action._executeCurrent(ActionEvent.CreateNew(sourceMesh));
  1041. sourceMesh._intersectionsInProgress.push(otherMesh);
  1042. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1043. sourceMesh._intersectionsInProgress.push(otherMesh);
  1044. }
  1045. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1046. action._executeCurrent(ActionEvent.CreateNew(sourceMesh));
  1047. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  1048. if (indexOfOther > -1) {
  1049. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  1050. }
  1051. }
  1052. }
  1053. }
  1054. }
  1055. }
  1056. public render(): void {
  1057. var startDate = Tools.Now;
  1058. this._particlesDuration = 0;
  1059. this._spritesDuration = 0;
  1060. this._activeParticles = 0;
  1061. this._renderDuration = 0;
  1062. this._renderTargetsDuration = 0;
  1063. this._evaluateActiveMeshesDuration = 0;
  1064. this._totalVertices = 0;
  1065. this._activeVertices = 0;
  1066. this._activeBones = 0;
  1067. this.getEngine().resetDrawCalls();
  1068. this._meshesForIntersections.reset();
  1069. this.resetCachedMaterial();
  1070. Tools.StartPerformanceCounter("Scene rendering");
  1071. // Actions
  1072. if (this.actionManager) {
  1073. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger, null);
  1074. }
  1075. // Before render
  1076. if (this.beforeRender) {
  1077. this.beforeRender();
  1078. }
  1079. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  1080. this._onBeforeRenderCallbacks[callbackIndex]();
  1081. }
  1082. // Animations
  1083. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  1084. this._animationRatio = deltaTime * (60.0 / 1000.0);
  1085. this._animate();
  1086. // Physics
  1087. if (this._physicsEngine) {
  1088. Tools.StartPerformanceCounter("Physics");
  1089. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  1090. Tools.EndPerformanceCounter("Physics");
  1091. }
  1092. // Customs render targets
  1093. var beforeRenderTargetDate = Tools.Now;
  1094. var engine = this.getEngine();
  1095. var currentActiveCamera = this.activeCamera;
  1096. if (this.renderTargetsEnabled) {
  1097. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1098. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  1099. var renderTarget = this.customRenderTargets[customIndex];
  1100. if (renderTarget._shouldRender()) {
  1101. this._renderId++;
  1102. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  1103. if (!this.activeCamera)
  1104. throw new Error("Active camera not set");
  1105. // Viewport
  1106. engine.setViewport(this.activeCamera.viewport);
  1107. // Camera
  1108. this.updateTransformMatrix();
  1109. renderTarget.render();
  1110. }
  1111. }
  1112. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1113. this._renderId++;
  1114. }
  1115. if (this.customRenderTargets.length > 0) { // Restore back buffer
  1116. engine.restoreDefaultFramebuffer();
  1117. }
  1118. this._renderTargetsDuration += Tools.Now - beforeRenderTargetDate;
  1119. this.activeCamera = currentActiveCamera;
  1120. // Procedural textures
  1121. if (this.proceduralTexturesEnabled) {
  1122. Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1123. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  1124. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  1125. if (proceduralTexture._shouldRender()) {
  1126. proceduralTexture.render();
  1127. }
  1128. }
  1129. Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1130. }
  1131. // Clear
  1132. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  1133. // Shadows
  1134. if (this.shadowsEnabled) {
  1135. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  1136. var light = this.lights[lightIndex];
  1137. var shadowGenerator = light.getShadowGenerator();
  1138. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  1139. this._renderTargets.push(shadowGenerator.getShadowMap());
  1140. }
  1141. }
  1142. }
  1143. // Depth renderer
  1144. if (this._depthRenderer) {
  1145. this._renderTargets.push(this._depthRenderer.getDepthMap());
  1146. }
  1147. // RenderPipeline
  1148. this.postProcessRenderPipelineManager.update();
  1149. // Multi-cameras?
  1150. if (this.activeCameras.length > 0) {
  1151. var currentRenderId = this._renderId;
  1152. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  1153. this._renderId = currentRenderId;
  1154. this._processSubCameras(this.activeCameras[cameraIndex]);
  1155. }
  1156. } else {
  1157. if (!this.activeCamera) {
  1158. throw new Error("No camera defined");
  1159. }
  1160. this._processSubCameras(this.activeCamera);
  1161. }
  1162. // Intersection checks
  1163. this._checkIntersections();
  1164. // Update the audio listener attached to the camera
  1165. this._updateAudioParameters();
  1166. // After render
  1167. if (this.afterRender) {
  1168. this.afterRender();
  1169. }
  1170. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  1171. this._onAfterRenderCallbacks[callbackIndex]();
  1172. }
  1173. // Cleaning
  1174. for (var index = 0; index < this._toBeDisposed.length; index++) {
  1175. this._toBeDisposed.data[index].dispose();
  1176. this._toBeDisposed[index] = null;
  1177. }
  1178. this._toBeDisposed.reset();
  1179. Tools.EndPerformanceCounter("Scene rendering");
  1180. this._lastFrameDuration = Tools.Now - startDate;
  1181. }
  1182. private _updateAudioParameters() {
  1183. var listeningCamera: Camera;
  1184. var audioEngine = Engine.audioEngine;
  1185. if (this.activeCameras.length > 0) {
  1186. listeningCamera = this.activeCameras[0];
  1187. } else {
  1188. listeningCamera = this.activeCamera;
  1189. }
  1190. if (listeningCamera && audioEngine.canUseWebAudio) {
  1191. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  1192. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  1193. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  1194. cameraDirection.normalize();
  1195. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  1196. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1197. var sound = this.mainSoundTrack.soundCollection[i];
  1198. if (sound.useCustomAttenuation) {
  1199. sound.updateDistanceFromListener();
  1200. }
  1201. }
  1202. for (i = 0; i < this.soundTracks.length; i++) {
  1203. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1204. sound = this.soundTracks[i].soundCollection[j];
  1205. if (sound.useCustomAttenuation) {
  1206. sound.updateDistanceFromListener();
  1207. }
  1208. }
  1209. }
  1210. }
  1211. }
  1212. public enableDepthRenderer(): DepthRenderer {
  1213. if (this._depthRenderer) {
  1214. return this._depthRenderer;
  1215. }
  1216. this._depthRenderer = new DepthRenderer(this);
  1217. return this._depthRenderer;
  1218. }
  1219. public disableDepthRenderer(): void {
  1220. if (!this._depthRenderer) {
  1221. return;
  1222. }
  1223. this._depthRenderer.dispose();
  1224. this._depthRenderer = null;
  1225. }
  1226. public dispose(): void {
  1227. this.beforeRender = null;
  1228. this.afterRender = null;
  1229. this.skeletons = [];
  1230. this._boundingBoxRenderer.dispose();
  1231. if (this._depthRenderer) {
  1232. this._depthRenderer.dispose();
  1233. }
  1234. // Debug layer
  1235. this.debugLayer.hide();
  1236. // Events
  1237. if (this.onDispose) {
  1238. this.onDispose();
  1239. }
  1240. this._onBeforeRenderCallbacks = [];
  1241. this._onAfterRenderCallbacks = [];
  1242. this.detachControl();
  1243. // Release sounds & sounds tracks
  1244. this.mainSoundTrack.dispose();
  1245. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  1246. this.soundTracks[scIndex].dispose();
  1247. }
  1248. // Detach cameras
  1249. var canvas = this._engine.getRenderingCanvas();
  1250. var index;
  1251. for (index = 0; index < this.cameras.length; index++) {
  1252. this.cameras[index].detachControl(canvas);
  1253. }
  1254. // Release lights
  1255. while (this.lights.length) {
  1256. this.lights[0].dispose();
  1257. }
  1258. // Release meshes
  1259. while (this.meshes.length) {
  1260. this.meshes[0].dispose(true);
  1261. }
  1262. // Release cameras
  1263. while (this.cameras.length) {
  1264. this.cameras[0].dispose();
  1265. }
  1266. // Release materials
  1267. while (this.materials.length) {
  1268. this.materials[0].dispose();
  1269. }
  1270. // Release particles
  1271. while (this.particleSystems.length) {
  1272. this.particleSystems[0].dispose();
  1273. }
  1274. // Release sprites
  1275. while (this.spriteManagers.length) {
  1276. this.spriteManagers[0].dispose();
  1277. }
  1278. // Release layers
  1279. while (this.layers.length) {
  1280. this.layers[0].dispose();
  1281. }
  1282. // Release textures
  1283. while (this.textures.length) {
  1284. this.textures[0].dispose();
  1285. }
  1286. // Post-processes
  1287. this.postProcessManager.dispose();
  1288. // Physics
  1289. if (this._physicsEngine) {
  1290. this.disablePhysicsEngine();
  1291. }
  1292. // Remove from engine
  1293. index = this._engine.scenes.indexOf(this);
  1294. if (index > -1) {
  1295. this._engine.scenes.splice(index, 1);
  1296. }
  1297. this._engine.wipeCaches();
  1298. }
  1299. // Collisions
  1300. public _getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, finalPosition: Vector3, excludedMesh: AbstractMesh = null): void {
  1301. position.divideToRef(collider.radius, this._scaledPosition);
  1302. velocity.divideToRef(collider.radius, this._scaledVelocity);
  1303. collider.retry = 0;
  1304. collider.initialVelocity = this._scaledVelocity;
  1305. collider.initialPosition = this._scaledPosition;
  1306. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  1307. finalPosition.multiplyInPlace(collider.radius);
  1308. }
  1309. private _collideWithWorld(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, finalPosition: Vector3, excludedMesh: AbstractMesh = null): void {
  1310. var closeDistance = Engine.CollisionsEpsilon * 10.0;
  1311. if (collider.retry >= maximumRetry) {
  1312. finalPosition.copyFrom(position);
  1313. return;
  1314. }
  1315. collider._initialize(position, velocity, closeDistance);
  1316. // Check all meshes
  1317. for (var index = 0; index < this.meshes.length; index++) {
  1318. var mesh = this.meshes[index];
  1319. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  1320. mesh._checkCollision(collider);
  1321. }
  1322. }
  1323. if (!collider.collisionFound) {
  1324. position.addToRef(velocity, finalPosition);
  1325. return;
  1326. }
  1327. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  1328. collider._getResponse(position, velocity);
  1329. }
  1330. if (velocity.length() <= closeDistance) {
  1331. finalPosition.copyFrom(position);
  1332. return;
  1333. }
  1334. collider.retry++;
  1335. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  1336. }
  1337. // Octrees
  1338. public getWorldExtends(): { min: Vector3; max: Vector3 } {
  1339. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1340. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1341. for (var index = 0; index < this.meshes.length; index++) {
  1342. var mesh = this.meshes[index];
  1343. mesh.computeWorldMatrix(true);
  1344. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  1345. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  1346. Tools.CheckExtends(minBox, min, max);
  1347. Tools.CheckExtends(maxBox, min, max);
  1348. }
  1349. return {
  1350. min: min,
  1351. max: max
  1352. };
  1353. }
  1354. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  1355. if (!this._selectionOctree) {
  1356. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  1357. }
  1358. var worldExtends = this.getWorldExtends();
  1359. // Update octree
  1360. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  1361. return this._selectionOctree;
  1362. }
  1363. // Picking
  1364. public createPickingRay(x: number, y: number, world: Matrix, camera: Camera): Ray {
  1365. var engine = this._engine;
  1366. if (!camera) {
  1367. if (!this.activeCamera)
  1368. throw new Error("Active camera not set");
  1369. camera = this.activeCamera;
  1370. }
  1371. var cameraViewport = camera.viewport;
  1372. var viewport = cameraViewport.toGlobal(engine);
  1373. // Moving coordinates to local viewport world
  1374. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  1375. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  1376. return Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  1377. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  1378. }
  1379. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): PickingInfo {
  1380. var pickingInfo = null;
  1381. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  1382. var mesh = this.meshes[meshIndex];
  1383. if (predicate) {
  1384. if (!predicate(mesh)) {
  1385. continue;
  1386. }
  1387. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  1388. continue;
  1389. }
  1390. var world = mesh.getWorldMatrix();
  1391. var ray = rayFunction(world);
  1392. var result = mesh.intersects(ray, fastCheck);
  1393. if (!result || !result.hit)
  1394. continue;
  1395. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  1396. continue;
  1397. pickingInfo = result;
  1398. if (fastCheck) {
  1399. break;
  1400. }
  1401. }
  1402. return pickingInfo || new PickingInfo();
  1403. }
  1404. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  1405. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  1406. /// <param name="x">X position on screen</param>
  1407. /// <param name="y">Y position on screen</param>
  1408. /// <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>
  1409. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  1410. /// <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>
  1411. return this._internalPick(world => this.createPickingRay(x, y, world, camera), predicate, fastCheck);
  1412. }
  1413. public pickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean, fastCheck?: boolean) {
  1414. return this._internalPick(world => {
  1415. if (!this._pickWithRayInverseMatrix) {
  1416. this._pickWithRayInverseMatrix = Matrix.Identity();
  1417. }
  1418. world.invertToRef(this._pickWithRayInverseMatrix);
  1419. return Ray.Transform(ray, this._pickWithRayInverseMatrix);
  1420. }, predicate, fastCheck);
  1421. }
  1422. public setPointerOverMesh(mesh: AbstractMesh): void {
  1423. if (this._pointerOverMesh === mesh) {
  1424. return;
  1425. }
  1426. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1427. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  1428. }
  1429. this._pointerOverMesh = mesh;
  1430. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1431. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  1432. }
  1433. }
  1434. public getPointerOverMesh(): AbstractMesh {
  1435. return this._pointerOverMesh;
  1436. }
  1437. // Physics
  1438. public getPhysicsEngine(): PhysicsEngine {
  1439. return this._physicsEngine;
  1440. }
  1441. public enablePhysics(gravity: Vector3, plugin?: IPhysicsEnginePlugin): boolean {
  1442. if (this._physicsEngine) {
  1443. return true;
  1444. }
  1445. this._physicsEngine = new PhysicsEngine(plugin);
  1446. if (!this._physicsEngine.isSupported()) {
  1447. this._physicsEngine = null;
  1448. return false;
  1449. }
  1450. this._physicsEngine._initialize(gravity);
  1451. return true;
  1452. }
  1453. public disablePhysicsEngine(): void {
  1454. if (!this._physicsEngine) {
  1455. return;
  1456. }
  1457. this._physicsEngine.dispose();
  1458. this._physicsEngine = undefined;
  1459. }
  1460. public isPhysicsEnabled(): boolean {
  1461. return this._physicsEngine !== undefined;
  1462. }
  1463. public setGravity(gravity: Vector3): void {
  1464. if (!this._physicsEngine) {
  1465. return;
  1466. }
  1467. this._physicsEngine._setGravity(gravity);
  1468. }
  1469. public createCompoundImpostor(parts: any, options: PhysicsBodyCreationOptions): any {
  1470. if (parts.parts) { // Old API
  1471. options = parts;
  1472. parts = parts.parts;
  1473. }
  1474. if (!this._physicsEngine) {
  1475. return null;
  1476. }
  1477. for (var index = 0; index < parts.length; index++) {
  1478. var mesh = parts[index].mesh;
  1479. mesh._physicImpostor = parts[index].impostor;
  1480. mesh._physicsMass = options.mass / parts.length;
  1481. mesh._physicsFriction = options.friction;
  1482. mesh._physicRestitution = options.restitution;
  1483. }
  1484. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  1485. }
  1486. public deleteCompoundImpostor(compound: any): void {
  1487. for (var index = 0; index < compound.parts.length; index++) {
  1488. var mesh = compound.parts[index].mesh;
  1489. mesh._physicImpostor = PhysicsEngine.NoImpostor;
  1490. this._physicsEngine._unregisterMesh(mesh);
  1491. }
  1492. }
  1493. // Misc.
  1494. public createDefaultCameraOrLight() {
  1495. // Light
  1496. if (this.lights.length === 0) {
  1497. new HemisphericLight("default light", Vector3.Up(), this);
  1498. }
  1499. // Camera
  1500. if (!this.activeCamera) {
  1501. var camera = new FreeCamera("default camera", Vector3.Zero(), this);
  1502. // Compute position
  1503. var worldExtends = this.getWorldExtends();
  1504. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  1505. camera.position = new Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  1506. camera.setTarget(worldCenter);
  1507. this.activeCamera = camera;
  1508. }
  1509. }
  1510. // Tags
  1511. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  1512. if (tagsQuery === undefined) {
  1513. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  1514. return list;
  1515. }
  1516. var listByTags = [];
  1517. forEach = forEach || ((item: any) => { return; });
  1518. for (var i in list) {
  1519. var item = list[i];
  1520. if (Tags.MatchesQuery(item, tagsQuery)) {
  1521. listByTags.push(item);
  1522. forEach(item);
  1523. }
  1524. }
  1525. return listByTags;
  1526. }
  1527. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  1528. return this._getByTags(this.meshes, tagsQuery, forEach);
  1529. }
  1530. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  1531. return this._getByTags(this.cameras, tagsQuery, forEach);
  1532. }
  1533. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  1534. return this._getByTags(this.lights, tagsQuery, forEach);
  1535. }
  1536. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  1537. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  1538. }
  1539. }
  1540. }