babylon.scene.ts 58 KB

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