babylon.scene.ts 175 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394
  1. module BABYLON {
  2. export interface IDisposable {
  3. dispose(): void;
  4. }
  5. class ClickInfo {
  6. private _singleClick = false;
  7. private _doubleClick = false;
  8. private _hasSwiped = false;
  9. private _ignore = false;
  10. public get singleClick(): boolean {
  11. return this._singleClick;
  12. }
  13. public get doubleClick(): boolean {
  14. return this._doubleClick;
  15. }
  16. public get hasSwiped(): boolean {
  17. return this._hasSwiped;
  18. }
  19. public get ignore(): boolean {
  20. return this._ignore;
  21. }
  22. public set singleClick(b: boolean) {
  23. this._singleClick = b;
  24. }
  25. public set doubleClick(b: boolean) {
  26. this._doubleClick = b;
  27. }
  28. public set hasSwiped(b: boolean) {
  29. this._hasSwiped = b;
  30. }
  31. public set ignore(b: boolean) {
  32. this._ignore = b;
  33. }
  34. }
  35. /**
  36. * This class is used by the onRenderingGroupObservable
  37. */
  38. export class RenderingGroupInfo {
  39. /**
  40. * The Scene that being rendered
  41. */
  42. scene: Scene;
  43. /**
  44. * The camera currently used for the rendering pass
  45. */
  46. camera: Nullable<Camera>;
  47. /**
  48. * The ID of the renderingGroup being processed
  49. */
  50. renderingGroupId: number;
  51. /**
  52. * The rendering stage, can be either STAGE_PRECLEAR, STAGE_PREOPAQUE, STAGE_PRETRANSPARENT, STAGE_POSTTRANSPARENT
  53. */
  54. renderStage: number;
  55. /**
  56. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  57. * This stage will be fired no matter what
  58. */
  59. static STAGE_PRECLEAR = 1;
  60. /**
  61. * Called before opaque object are rendered.
  62. * This stage will be fired only if there's 3D Opaque content to render
  63. */
  64. static STAGE_PREOPAQUE = 2;
  65. /**
  66. * Called after the opaque objects are rendered and before the transparent ones
  67. * This stage will be fired only if there's 3D transparent content to render
  68. */
  69. static STAGE_PRETRANSPARENT = 3;
  70. /**
  71. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  72. * This stage will be fired no matter what
  73. */
  74. static STAGE_POSTTRANSPARENT = 4;
  75. }
  76. /**
  77. * Represents a scene to be rendered by the engine.
  78. * @see http://doc.babylonjs.com/page.php?p=21911
  79. */
  80. export class Scene implements IAnimatable {
  81. // Statics
  82. private static _FOGMODE_NONE = 0;
  83. private static _FOGMODE_EXP = 1;
  84. private static _FOGMODE_EXP2 = 2;
  85. private static _FOGMODE_LINEAR = 3;
  86. private static _uniqueIdCounter = 0;
  87. public static MinDeltaTime = 1.0;
  88. public static MaxDeltaTime = 1000.0;
  89. /** The fog is deactivated */
  90. public static get FOGMODE_NONE(): number {
  91. return Scene._FOGMODE_NONE;
  92. }
  93. /** The fog density is following an exponential function */
  94. public static get FOGMODE_EXP(): number {
  95. return Scene._FOGMODE_EXP;
  96. }
  97. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  98. public static get FOGMODE_EXP2(): number {
  99. return Scene._FOGMODE_EXP2;
  100. }
  101. /** The fog density is following a linear function. */
  102. public static get FOGMODE_LINEAR(): number {
  103. return Scene._FOGMODE_LINEAR;
  104. }
  105. // Members
  106. public autoClear = true;
  107. public autoClearDepthAndStencil = true;
  108. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  109. public ambientColor = new Color3(0, 0, 0);
  110. public _environmentBRDFTexture: BaseTexture;
  111. protected _environmentTexture: BaseTexture;
  112. /**
  113. * Texture used in all pbr material as the reflection texture.
  114. * As in the majority of the scene they are the same (exception for multi room and so on),
  115. * this is easier to reference from here than from all the materials.
  116. */
  117. public get environmentTexture(): BaseTexture {
  118. return this._environmentTexture;
  119. }
  120. /**
  121. * Texture used in all pbr material as the reflection texture.
  122. * As in the majority of the scene they are the same (exception for multi room and so on),
  123. * this is easier to set here than in all the materials.
  124. */
  125. public set environmentTexture(value: BaseTexture) {
  126. if (this._environmentTexture === value) {
  127. return;
  128. }
  129. this._environmentTexture = value;
  130. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  131. }
  132. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  133. /**
  134. * Default image processing configuration used either in the rendering
  135. * Forward main pass or through the imageProcessingPostProcess if present.
  136. * As in the majority of the scene they are the same (exception for multi camera),
  137. * this is easier to reference from here than from all the materials and post process.
  138. *
  139. * No setter as we it is a shared configuration, you can set the values instead.
  140. */
  141. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  142. return this._imageProcessingConfiguration;
  143. }
  144. public forceWireframe = false;
  145. private _forcePointsCloud = false;
  146. public set forcePointsCloud(value: boolean) {
  147. if (this._forcePointsCloud === value) {
  148. return;
  149. }
  150. this._forcePointsCloud = value;
  151. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  152. }
  153. public get forcePointsCloud(): boolean {
  154. return this._forcePointsCloud;
  155. }
  156. public forceShowBoundingBoxes = false;
  157. public clipPlane: Nullable<Plane>;
  158. public animationsEnabled = true;
  159. public constantlyUpdateMeshUnderPointer = false;
  160. public hoverCursor = "pointer";
  161. public defaultCursor: string = "";
  162. /**
  163. * This is used to call preventDefault() on pointer down
  164. * in order to block unwanted artifacts like system double clicks
  165. */
  166. public preventDefaultOnPointerDown = true;
  167. // Metadata
  168. public metadata: any = null;
  169. public loadingPluginName: string;
  170. // Events
  171. private _spritePredicate: (sprite: Sprite) => boolean;
  172. /**
  173. * An event triggered when the scene is disposed.
  174. * @type {BABYLON.Observable}
  175. */
  176. public onDisposeObservable = new Observable<Scene>();
  177. private _onDisposeObserver: Nullable<Observer<Scene>>;
  178. /** A function to be executed when this scene is disposed. */
  179. public set onDispose(callback: () => void) {
  180. if (this._onDisposeObserver) {
  181. this.onDisposeObservable.remove(this._onDisposeObserver);
  182. }
  183. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  184. }
  185. /**
  186. * An event triggered before rendering the scene (right after animations and physcis)
  187. * @type {BABYLON.Observable}
  188. */
  189. public onBeforeRenderObservable = new Observable<Scene>();
  190. private _onBeforeRenderObserver: Nullable<Observer<Scene>>;
  191. /** A function to be executed before rendering this scene */
  192. public set beforeRender(callback: Nullable<() => void>) {
  193. if (this._onBeforeRenderObserver) {
  194. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  195. }
  196. if (callback) {
  197. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  198. }
  199. }
  200. /**
  201. * An event triggered after rendering the scene
  202. * @type {BABYLON.Observable}
  203. */
  204. public onAfterRenderObservable = new Observable<Scene>();
  205. private _onAfterRenderObserver: Nullable<Observer<Scene>>;
  206. /** A function to be executed after rendering this scene */
  207. public set afterRender(callback: Nullable<() => void>) {
  208. if (this._onAfterRenderObserver) {
  209. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  210. }
  211. if (callback) {
  212. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  213. }
  214. }
  215. /**
  216. * An event triggered before animating the scene
  217. * @type {BABYLON.Observable}
  218. */
  219. public onBeforeAnimationsObservable = new Observable<Scene>();
  220. /**
  221. * An event triggered before draw calls are ready to be sent
  222. * @type {BABYLON.Observable}
  223. */
  224. public onBeforeDrawPhaseObservable = new Observable<Scene>();
  225. /**
  226. * An event triggered after draw calls have been sent
  227. * @type {BABYLON.Observable}
  228. */
  229. public onAfterDrawPhaseObservable = new Observable<Scene>();
  230. /**
  231. * An event triggered when the scene is ready
  232. * @type {BABYLON.Observable}
  233. */
  234. public onReadyObservable = new Observable<Scene>();
  235. /**
  236. * An event triggered before rendering a camera
  237. * @type {BABYLON.Observable}
  238. */
  239. public onBeforeCameraRenderObservable = new Observable<Camera>();
  240. private _onBeforeCameraRenderObserver: Nullable<Observer<Camera>>;
  241. public set beforeCameraRender(callback: () => void) {
  242. if (this._onBeforeCameraRenderObserver) {
  243. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  244. }
  245. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  246. }
  247. /**
  248. * An event triggered after rendering a camera
  249. * @type {BABYLON.Observable}
  250. */
  251. public onAfterCameraRenderObservable = new Observable<Camera>();
  252. private _onAfterCameraRenderObserver: Nullable<Observer<Camera>>;
  253. public set afterCameraRender(callback: () => void) {
  254. if (this._onAfterCameraRenderObserver) {
  255. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  256. }
  257. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  258. }
  259. /**
  260. * An event triggered when active meshes evaluation is about to start
  261. * @type {BABYLON.Observable}
  262. */
  263. public onBeforeActiveMeshesEvaluationObservable = new Observable<Scene>();
  264. /**
  265. * An event triggered when active meshes evaluation is done
  266. * @type {BABYLON.Observable}
  267. */
  268. public onAfterActiveMeshesEvaluationObservable = new Observable<Scene>();
  269. /**
  270. * An event triggered when particles rendering is about to start
  271. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  272. * @type {BABYLON.Observable}
  273. */
  274. public onBeforeParticlesRenderingObservable = new Observable<Scene>();
  275. /**
  276. * An event triggered when particles rendering is done
  277. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  278. * @type {BABYLON.Observable}
  279. */
  280. public onAfterParticlesRenderingObservable = new Observable<Scene>();
  281. /**
  282. * An event triggered when sprites rendering is about to start
  283. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  284. * @type {BABYLON.Observable}
  285. */
  286. public onBeforeSpritesRenderingObservable = new Observable<Scene>();
  287. /**
  288. * An event triggered when sprites rendering is done
  289. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  290. * @type {BABYLON.Observable}
  291. */
  292. public onAfterSpritesRenderingObservable = new Observable<Scene>();
  293. /**
  294. * An event triggered when a camera is created
  295. * @type {BABYLON.Observable}
  296. */
  297. public onNewCameraAddedObservable = new Observable<Camera>();
  298. /**
  299. * An event triggered when a camera is removed
  300. * @type {BABYLON.Observable}
  301. */
  302. public onCameraRemovedObservable = new Observable<Camera>();
  303. /**
  304. * An event triggered when a light is created
  305. * @type {BABYLON.Observable}
  306. */
  307. public onNewLightAddedObservable = new Observable<Light>();
  308. /**
  309. * An event triggered when a light is removed
  310. * @type {BABYLON.Observable}
  311. */
  312. public onLightRemovedObservable = new Observable<Light>();
  313. /**
  314. * An event triggered when a geometry is created
  315. * @type {BABYLON.Observable}
  316. */
  317. public onNewGeometryAddedObservable = new Observable<Geometry>();
  318. /**
  319. * An event triggered when a geometry is removed
  320. * @type {BABYLON.Observable}
  321. */
  322. public onGeometryRemovedObservable = new Observable<Geometry>();
  323. /**
  324. * An event triggered when a mesh is created
  325. * @type {BABYLON.Observable}
  326. */
  327. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  328. /**
  329. * An event triggered when a mesh is removed
  330. * @type {BABYLON.Observable}
  331. */
  332. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  333. /**
  334. * An event triggered when render targets are about to be rendered
  335. * Can happen multiple times per frame.
  336. * @type {BABYLON.Observable}
  337. */
  338. public OnBeforeRenderTargetsRenderObservable = new Observable<Scene>();
  339. /**
  340. * An event triggered when render targets were rendered.
  341. * Can happen multiple times per frame.
  342. * @type {BABYLON.Observable}
  343. */
  344. public OnAfterRenderTargetsRenderObservable = new Observable<Scene>();
  345. /**
  346. * An event triggered before calculating deterministic simulation step
  347. * @type {BABYLON.Observable}
  348. */
  349. public onBeforeStepObservable = new Observable<Scene>();
  350. /**
  351. * An event triggered after calculating deterministic simulation step
  352. * @type {BABYLON.Observable}
  353. */
  354. public onAfterStepObservable = new Observable<Scene>();
  355. /**
  356. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  357. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  358. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  359. */
  360. public onRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  361. // Animations
  362. public animations: Animation[] = [];
  363. // Pointers
  364. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  365. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  366. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  367. private _onPointerMove: (evt: PointerEvent) => void;
  368. private _onPointerDown: (evt: PointerEvent) => void;
  369. private _onPointerUp: (evt: PointerEvent) => void;
  370. /** Deprecated. Use onPointerObservable instead */
  371. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  372. /** Deprecated. Use onPointerObservable instead */
  373. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  374. /** Deprecated. Use onPointerObservable instead */
  375. public onPointerUp: (evt: PointerEvent, pickInfo: Nullable<PickingInfo>) => void;
  376. /** Deprecated. Use onPointerObservable instead */
  377. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  378. // Gamepads
  379. private _gamepadManager: Nullable<GamepadManager>;
  380. public get gamepadManager(): GamepadManager {
  381. if (!this._gamepadManager) {
  382. this._gamepadManager = new GamepadManager();
  383. }
  384. return this._gamepadManager;
  385. }
  386. /**
  387. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  388. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  389. */
  390. public onPrePointerObservable = new Observable<PointerInfoPre>();
  391. /**
  392. * Observable event triggered each time an input event is received from the rendering canvas
  393. */
  394. public onPointerObservable = new Observable<PointerInfo>();
  395. public get unTranslatedPointer(): Vector2 {
  396. return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  397. }
  398. /** The distance in pixel that you have to move to prevent some events */
  399. public static DragMovementThreshold = 10; // in pixels
  400. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  401. public static LongPressDelay = 500; // in milliseconds
  402. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  403. public static DoubleClickDelay = 300; // in milliseconds
  404. /** If you need to check double click without raising a single click at first click, enable this flag */
  405. public static ExclusiveDoubleClickMode = false;
  406. private _initClickEvent: (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  407. private _initActionManager: (act: Nullable<ActionManager>, clickInfo: ClickInfo) => Nullable<ActionManager>;
  408. private _delayedSimpleClick: (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => void;
  409. private _delayedSimpleClickTimeout: number;
  410. private _previousDelayedSimpleClickTimeout: number;
  411. private _meshPickProceed = false;
  412. private _previousButtonPressed: number;
  413. private _previousHasSwiped = false;
  414. private _currentPickResult: Nullable<PickingInfo> = null;
  415. private _previousPickResult: Nullable<PickingInfo> = null;
  416. private _totalPointersPressed = 0;
  417. private _doubleClickOccured = false;
  418. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  419. public cameraToUseForPointers: Nullable<Camera> = null;
  420. private _pointerX: number;
  421. private _pointerY: number;
  422. private _unTranslatedPointerX: number;
  423. private _unTranslatedPointerY: number;
  424. private _startingPointerPosition = new Vector2(0, 0);
  425. private _previousStartingPointerPosition = new Vector2(0, 0);
  426. private _startingPointerTime = 0;
  427. private _previousStartingPointerTime = 0;
  428. // Deterministic lockstep
  429. private _timeAccumulator: number = 0;
  430. private _currentStepId: number = 0;
  431. private _currentInternalStep: number = 0;
  432. // Mirror
  433. public _mirroredCameraPosition: Nullable<Vector3>;
  434. // Keyboard
  435. /**
  436. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  437. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  438. */
  439. public onPreKeyboardObservable = new Observable<KeyboardInfoPre>();
  440. /**
  441. * Observable event triggered each time an keyboard event is received from the hosting window
  442. */
  443. public onKeyboardObservable = new Observable<KeyboardInfo>();
  444. private _onKeyDown: (evt: Event) => void;
  445. private _onKeyUp: (evt: Event) => void;
  446. private _onCanvasFocusObserver: Nullable<Observer<Engine>>;
  447. private _onCanvasBlurObserver: Nullable<Observer<Engine>>;
  448. // Coordinate system
  449. /**
  450. * use right-handed coordinate system on this scene.
  451. * @type {boolean}
  452. */
  453. private _useRightHandedSystem = false;
  454. public set useRightHandedSystem(value: boolean) {
  455. if (this._useRightHandedSystem === value) {
  456. return;
  457. }
  458. this._useRightHandedSystem = value;
  459. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  460. }
  461. public get useRightHandedSystem(): boolean {
  462. return this._useRightHandedSystem;
  463. }
  464. public setStepId(newStepId: number): void {
  465. this._currentStepId = newStepId;
  466. };
  467. public getStepId(): number {
  468. return this._currentStepId;
  469. };
  470. public getInternalStep(): number {
  471. return this._currentInternalStep;
  472. };
  473. // Fog
  474. private _fogEnabled = true;
  475. /**
  476. * is fog enabled on this scene.
  477. */
  478. public set fogEnabled(value: boolean) {
  479. if (this._fogEnabled === value) {
  480. return;
  481. }
  482. this._fogEnabled = value;
  483. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  484. }
  485. public get fogEnabled(): boolean {
  486. return this._fogEnabled;
  487. }
  488. private _fogMode = Scene.FOGMODE_NONE;
  489. public set fogMode(value: number) {
  490. if (this._fogMode === value) {
  491. return;
  492. }
  493. this._fogMode = value;
  494. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  495. }
  496. public get fogMode(): number {
  497. return this._fogMode;
  498. }
  499. public fogColor = new Color3(0.2, 0.2, 0.3);
  500. public fogDensity = 0.1;
  501. public fogStart = 0;
  502. public fogEnd = 1000.0;
  503. // Lights
  504. /**
  505. * is shadow enabled on this scene.
  506. * @type {boolean}
  507. */
  508. private _shadowsEnabled = true;
  509. public set shadowsEnabled(value: boolean) {
  510. if (this._shadowsEnabled === value) {
  511. return;
  512. }
  513. this._shadowsEnabled = value;
  514. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  515. }
  516. public get shadowsEnabled(): boolean {
  517. return this._shadowsEnabled;
  518. }
  519. /**
  520. * is light enabled on this scene.
  521. * @type {boolean}
  522. */
  523. private _lightsEnabled = true;
  524. public set lightsEnabled(value: boolean) {
  525. if (this._lightsEnabled === value) {
  526. return;
  527. }
  528. this._lightsEnabled = value;
  529. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  530. }
  531. public get lightsEnabled(): boolean {
  532. return this._lightsEnabled;
  533. }
  534. /**
  535. * All of the lights added to this scene.
  536. * @see BABYLON.Light
  537. * @type {BABYLON.Light[]}
  538. */
  539. public lights = new Array<Light>();
  540. // Cameras
  541. /** All of the cameras added to this scene. */
  542. public cameras = new Array<Camera>();
  543. /** All of the active cameras added to this scene. */
  544. public activeCameras = new Array<Camera>();
  545. /** The current active camera */
  546. public activeCamera: Nullable<Camera>;
  547. // Meshes
  548. /**
  549. * All of the (abstract) meshes added to this scene.
  550. * @see BABYLON.AbstractMesh
  551. * @type {BABYLON.AbstractMesh[]}
  552. */
  553. public meshes = new Array<AbstractMesh>();
  554. // Geometries
  555. private _geometries = new Array<Geometry>();
  556. public materials = new Array<Material>();
  557. public multiMaterials = new Array<MultiMaterial>();
  558. private _defaultMaterial: Material;
  559. /** The default material used on meshes when no material is affected */
  560. public get defaultMaterial(): Material {
  561. if (!this._defaultMaterial) {
  562. this._defaultMaterial = new StandardMaterial("default material", this);
  563. }
  564. return this._defaultMaterial;
  565. }
  566. /** The default material used on meshes when no material is affected */
  567. public set defaultMaterial(value: Material) {
  568. this._defaultMaterial = value;
  569. }
  570. // Textures
  571. private _texturesEnabled = true;
  572. public set texturesEnabled(value: boolean) {
  573. if (this._texturesEnabled === value) {
  574. return;
  575. }
  576. this._texturesEnabled = value;
  577. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  578. }
  579. public get texturesEnabled(): boolean {
  580. return this._texturesEnabled;
  581. }
  582. public textures = new Array<BaseTexture>();
  583. // Particles
  584. public particlesEnabled = true;
  585. public particleSystems = new Array<IParticleSystem>();
  586. // Sprites
  587. public spritesEnabled = true;
  588. public spriteManagers = new Array<SpriteManager>();
  589. // Layers
  590. public layers = new Array<Layer>();
  591. public highlightLayers = new Array<HighlightLayer>();
  592. // Skeletons
  593. private _skeletonsEnabled = true;
  594. public set skeletonsEnabled(value: boolean) {
  595. if (this._skeletonsEnabled === value) {
  596. return;
  597. }
  598. this._skeletonsEnabled = value;
  599. this.markAllMaterialsAsDirty(Material.AttributesDirtyFlag);
  600. }
  601. public get skeletonsEnabled(): boolean {
  602. return this._skeletonsEnabled;
  603. }
  604. public skeletons = new Array<Skeleton>();
  605. // Morph targets
  606. public morphTargetManagers = new Array<MorphTargetManager>();
  607. // Lens flares
  608. public lensFlaresEnabled = true;
  609. public lensFlareSystems = new Array<LensFlareSystem>();
  610. // Collisions
  611. public collisionsEnabled = true;
  612. private _workerCollisions: boolean;
  613. public collisionCoordinator: ICollisionCoordinator;
  614. /** Defines the gravity applied to this scene */
  615. public gravity = new Vector3(0, -9.807, 0);
  616. // Postprocesses
  617. public postProcesses = new Array<PostProcess>();
  618. public postProcessesEnabled = true;
  619. public postProcessManager: PostProcessManager;
  620. private _postProcessRenderPipelineManager: PostProcessRenderPipelineManager
  621. public get postProcessRenderPipelineManager(): PostProcessRenderPipelineManager {
  622. if (!this._postProcessRenderPipelineManager) {
  623. this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  624. }
  625. return this._postProcessRenderPipelineManager;
  626. }
  627. // Customs render targets
  628. public renderTargetsEnabled = true;
  629. public dumpNextRenderTargets = false;
  630. public customRenderTargets = new Array<RenderTargetTexture>();
  631. // Delay loading
  632. public useDelayedTextureLoading: boolean;
  633. // Imported meshes
  634. public importedMeshesFiles = new Array<String>();
  635. // Probes
  636. public probesEnabled = true;
  637. public reflectionProbes = new Array<ReflectionProbe>();
  638. // Database
  639. public database: Database;
  640. /**
  641. * This scene's action manager
  642. * @type {BABYLON.ActionManager}
  643. */
  644. public actionManager: ActionManager;
  645. public _actionManagers = new Array<ActionManager>();
  646. private _meshesForIntersections = new SmartArray<AbstractMesh>(256);
  647. // Procedural textures
  648. public proceduralTexturesEnabled = true;
  649. public _proceduralTextures = new Array<ProceduralTexture>();
  650. // Sound Tracks
  651. private _mainSoundTrack: SoundTrack;
  652. public soundTracks = new Array<SoundTrack>();
  653. private _audioEnabled = true;
  654. private _headphone = false;
  655. public get mainSoundTrack(): SoundTrack {
  656. if (!this._mainSoundTrack) {
  657. this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  658. }
  659. return this._mainSoundTrack;
  660. }
  661. // VR Helper
  662. public VRHelper: VRExperienceHelper;
  663. //Simplification Queue
  664. public simplificationQueue: SimplificationQueue;
  665. // Private
  666. private _engine: Engine;
  667. // Performance counters
  668. private _totalVertices = new PerfCounter();
  669. public _activeIndices = new PerfCounter();
  670. public _activeParticles = new PerfCounter();
  671. public _activeBones = new PerfCounter();
  672. private _animationRatio: number;
  673. private _animationTimeLast: number;
  674. private _animationTime: number = 0;
  675. public animationTimeScale: number = 1;
  676. public _cachedMaterial: Nullable<Material>;
  677. public _cachedEffect: Nullable<Effect>;
  678. public _cachedVisibility: Nullable<number>;
  679. private _renderId = 0;
  680. private _executeWhenReadyTimeoutId = -1;
  681. private _intermediateRendering = false;
  682. private _viewUpdateFlag = -1;
  683. private _projectionUpdateFlag = -1;
  684. private _alternateViewUpdateFlag = -1;
  685. private _alternateProjectionUpdateFlag = -1;
  686. public _toBeDisposed = new SmartArray<Nullable<IDisposable>>(256);
  687. private _pendingData = new Array();
  688. private _isDisposed = false;
  689. private _activeMeshes = new SmartArray<AbstractMesh>(256);
  690. private _processedMaterials = new SmartArray<Material>(256);
  691. private _renderTargets = new SmartArray<RenderTargetTexture>(256);
  692. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  693. private _activeSkeletons = new SmartArray<Skeleton>(32);
  694. private _softwareSkinnedMeshes = new SmartArray<Mesh>(32);
  695. private _renderingManager: RenderingManager;
  696. private _physicsEngine: Nullable<PhysicsEngine>;
  697. public _activeAnimatables = new Array<Animatable>();
  698. private _transformMatrix = Matrix.Zero();
  699. private _sceneUbo: UniformBuffer;
  700. private _alternateSceneUbo: UniformBuffer;
  701. private _pickWithRayInverseMatrix: Matrix;
  702. private _boundingBoxRenderer: BoundingBoxRenderer;
  703. private _outlineRenderer: OutlineRenderer;
  704. private _viewMatrix: Matrix;
  705. private _projectionMatrix: Matrix;
  706. private _alternateViewMatrix: Matrix;
  707. private _alternateProjectionMatrix: Matrix;
  708. private _alternateTransformMatrix: Matrix;
  709. private _useAlternateCameraConfiguration = false;
  710. private _alternateRendering = false;
  711. public _forcedViewPosition: Nullable<Vector3>;
  712. public get _isAlternateRenderingEnabled(): boolean {
  713. return this._alternateRendering;
  714. }
  715. private _frustumPlanes: Plane[];
  716. public get frustumPlanes(): Plane[] {
  717. return this._frustumPlanes;
  718. }
  719. public requireLightSorting = false;
  720. private _selectionOctree: Octree<AbstractMesh>;
  721. private _pointerOverMesh: Nullable<AbstractMesh>;
  722. private _pointerOverSprite: Nullable<Sprite>;
  723. private _debugLayer: DebugLayer;
  724. private _depthRenderer: Nullable<DepthRenderer>;
  725. private _geometryBufferRenderer: Nullable<GeometryBufferRenderer>;
  726. private _pickedDownMesh: Nullable<AbstractMesh>;
  727. private _pickedUpMesh: Nullable<AbstractMesh>;
  728. private _pickedDownSprite: Nullable<Sprite>;
  729. private _externalData: StringDictionary<Object>;
  730. private _uid: Nullable<string>;
  731. /**
  732. * @constructor
  733. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  734. */
  735. constructor(engine: Engine) {
  736. this._engine = engine || Engine.LastCreatedEngine;
  737. this._engine.scenes.push(this);
  738. this._uid = null;
  739. this._renderingManager = new RenderingManager(this);
  740. this.postProcessManager = new PostProcessManager(this);
  741. if (OutlineRenderer) {
  742. this._outlineRenderer = new OutlineRenderer(this);
  743. }
  744. if (Tools.IsWindowObjectExist()) {
  745. this.attachControl();
  746. }
  747. //simplification queue
  748. if (SimplificationQueue) {
  749. this.simplificationQueue = new SimplificationQueue();
  750. }
  751. //collision coordinator initialization. For now legacy per default.
  752. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  753. // Uniform Buffer
  754. this._createUbo();
  755. // Default Image processing definition.
  756. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  757. }
  758. // Properties
  759. public get debugLayer(): DebugLayer {
  760. if (!this._debugLayer) {
  761. this._debugLayer = new DebugLayer(this);
  762. }
  763. return this._debugLayer;
  764. }
  765. public set workerCollisions(enabled: boolean) {
  766. if (!BABYLON.CollisionCoordinatorLegacy) {
  767. return;
  768. }
  769. enabled = (enabled && !!Worker);
  770. this._workerCollisions = enabled;
  771. if (this.collisionCoordinator) {
  772. this.collisionCoordinator.destroy();
  773. }
  774. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  775. this.collisionCoordinator.init(this);
  776. }
  777. public get workerCollisions(): boolean {
  778. return this._workerCollisions;
  779. }
  780. public get selectionOctree(): Octree<AbstractMesh> {
  781. return this._selectionOctree;
  782. }
  783. /**
  784. * The mesh that is currently under the pointer.
  785. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  786. */
  787. public get meshUnderPointer(): Nullable<AbstractMesh> {
  788. return this._pointerOverMesh;
  789. }
  790. /**
  791. * Current on-screen X position of the pointer
  792. * @return {number} X position of the pointer
  793. */
  794. public get pointerX(): number {
  795. return this._pointerX;
  796. }
  797. /**
  798. * Current on-screen Y position of the pointer
  799. * @return {number} Y position of the pointer
  800. */
  801. public get pointerY(): number {
  802. return this._pointerY;
  803. }
  804. public getCachedMaterial(): Nullable<Material> {
  805. return this._cachedMaterial;
  806. }
  807. public getCachedEffect(): Nullable<Effect> {
  808. return this._cachedEffect;
  809. }
  810. public getCachedVisibility(): Nullable<number> {
  811. return this._cachedVisibility;
  812. }
  813. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  814. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  815. }
  816. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  817. if (!this._boundingBoxRenderer) {
  818. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  819. }
  820. return this._boundingBoxRenderer;
  821. }
  822. public getOutlineRenderer(): OutlineRenderer {
  823. return this._outlineRenderer;
  824. }
  825. public getEngine(): Engine {
  826. return this._engine;
  827. }
  828. public getTotalVertices(): number {
  829. return this._totalVertices.current;
  830. }
  831. public get totalVerticesPerfCounter(): PerfCounter {
  832. return this._totalVertices;
  833. }
  834. public getActiveIndices(): number {
  835. return this._activeIndices.current;
  836. }
  837. public get totalActiveIndicesPerfCounter(): PerfCounter {
  838. return this._activeIndices;
  839. }
  840. public getActiveParticles(): number {
  841. return this._activeParticles.current;
  842. }
  843. public get activeParticlesPerfCounter(): PerfCounter {
  844. return this._activeParticles;
  845. }
  846. public getActiveBones(): number {
  847. return this._activeBones.current;
  848. }
  849. public get activeBonesPerfCounter(): PerfCounter {
  850. return this._activeBones;
  851. }
  852. // Stats
  853. public getInterFramePerfCounter(): number {
  854. Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  855. return 0;
  856. }
  857. public get interFramePerfCounter(): Nullable<PerfCounter> {
  858. Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  859. return null;
  860. }
  861. public getLastFrameDuration(): number {
  862. Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  863. return 0;
  864. }
  865. public get lastFramePerfCounter(): Nullable<PerfCounter> {
  866. Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  867. return null;
  868. }
  869. public getEvaluateActiveMeshesDuration(): number {
  870. Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  871. return 0;
  872. }
  873. public get evaluateActiveMeshesDurationPerfCounter(): Nullable<PerfCounter> {
  874. Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  875. return null;
  876. }
  877. public getActiveMeshes(): SmartArray<AbstractMesh> {
  878. return this._activeMeshes;
  879. }
  880. public getRenderTargetsDuration(): number {
  881. Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  882. return 0;
  883. }
  884. public getRenderDuration(): number {
  885. Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  886. return 0;
  887. }
  888. public get renderDurationPerfCounter(): Nullable<PerfCounter> {
  889. Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  890. return null;
  891. }
  892. public getParticlesDuration(): number {
  893. Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  894. return 0;
  895. }
  896. public get particlesDurationPerfCounter(): Nullable<PerfCounter> {
  897. Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  898. return null;
  899. }
  900. public getSpritesDuration(): number {
  901. Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  902. return 0;
  903. }
  904. public get spriteDuractionPerfCounter(): Nullable<PerfCounter> {
  905. Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  906. return null;
  907. }
  908. public getAnimationRatio(): number {
  909. return this._animationRatio;
  910. }
  911. public getRenderId(): number {
  912. return this._renderId;
  913. }
  914. public incrementRenderId(): void {
  915. this._renderId++;
  916. }
  917. private _updatePointerPosition(evt: PointerEvent): void {
  918. var canvasRect = this._engine.getRenderingCanvasClientRect();
  919. if (!canvasRect) {
  920. return;
  921. }
  922. this._pointerX = evt.clientX - canvasRect.left;
  923. this._pointerY = evt.clientY - canvasRect.top;
  924. this._unTranslatedPointerX = this._pointerX;
  925. this._unTranslatedPointerY = this._pointerY;
  926. }
  927. private _createUbo(): void {
  928. this._sceneUbo = new UniformBuffer(this._engine, undefined, true);
  929. this._sceneUbo.addUniform("viewProjection", 16);
  930. this._sceneUbo.addUniform("view", 16);
  931. }
  932. private _createAlternateUbo(): void {
  933. this._alternateSceneUbo = new UniformBuffer(this._engine, undefined, true);
  934. this._alternateSceneUbo.addUniform("viewProjection", 16);
  935. this._alternateSceneUbo.addUniform("view", 16);
  936. }
  937. // Pointers handling
  938. /**
  939. * Use this method to simulate a pointer move on a mesh
  940. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  941. */
  942. public simulatePointerMove(pickResult: PickingInfo): Scene {
  943. let evt = new PointerEvent("pointermove");
  944. return this._processPointerMove(pickResult, evt);
  945. }
  946. private _processPointerMove(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  947. var canvas = this._engine.getRenderingCanvas();
  948. if (!canvas) {
  949. return this;
  950. }
  951. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  952. this.setPointerOverSprite(null);
  953. this.setPointerOverMesh(pickResult.pickedMesh);
  954. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  955. if (this._pointerOverMesh.actionManager.hoverCursor) {
  956. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  957. } else {
  958. canvas.style.cursor = this.hoverCursor;
  959. }
  960. } else {
  961. canvas.style.cursor = this.defaultCursor;
  962. }
  963. } else {
  964. this.setPointerOverMesh(null);
  965. // Sprites
  966. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  967. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  968. this.setPointerOverSprite(pickResult.pickedSprite);
  969. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  970. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  971. } else {
  972. canvas.style.cursor = this.hoverCursor;
  973. }
  974. } else {
  975. this.setPointerOverSprite(null);
  976. // Restore pointer
  977. canvas.style.cursor = this.defaultCursor;
  978. }
  979. }
  980. if (pickResult) {
  981. if (this.onPointerMove) {
  982. this.onPointerMove(evt, pickResult);
  983. }
  984. if (this.onPointerObservable.hasObservers()) {
  985. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  986. let pi = new PointerInfo(type, evt, pickResult);
  987. this.onPointerObservable.notifyObservers(pi, type);
  988. }
  989. }
  990. return this;
  991. }
  992. /**
  993. * Use this method to simulate a pointer down on a mesh
  994. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  995. */
  996. public simulatePointerDown(pickResult: PickingInfo): Scene {
  997. let evt = new PointerEvent("pointerdown");
  998. return this._processPointerDown(pickResult, evt);
  999. }
  1000. private _processPointerDown(pickResult: Nullable<PickingInfo>, evt: PointerEvent): Scene {
  1001. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  1002. this._pickedDownMesh = pickResult.pickedMesh;
  1003. var actionManager = pickResult.pickedMesh.actionManager;
  1004. if (actionManager) {
  1005. if (actionManager.hasPickTriggers) {
  1006. actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1007. switch (evt.button) {
  1008. case 0:
  1009. actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1010. break;
  1011. case 1:
  1012. actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1013. break;
  1014. case 2:
  1015. actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1016. break;
  1017. }
  1018. }
  1019. if (actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger)) {
  1020. window.setTimeout(() => {
  1021. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  1022. (mesh: AbstractMesh): boolean => (<boolean>(mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger) && mesh == this._pickedDownMesh)),
  1023. false, this.cameraToUseForPointers);
  1024. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  1025. if (this._totalPointersPressed !== 0 &&
  1026. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  1027. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  1028. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  1029. this._startingPointerTime = 0;
  1030. actionManager.processTrigger(ActionManager.OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1031. }
  1032. }
  1033. }, Scene.LongPressDelay);
  1034. }
  1035. }
  1036. }
  1037. if (pickResult) {
  1038. if (this.onPointerDown) {
  1039. this.onPointerDown(evt, pickResult);
  1040. }
  1041. if (this.onPointerObservable.hasObservers()) {
  1042. let type = PointerEventTypes.POINTERDOWN;
  1043. let pi = new PointerInfo(type, evt, pickResult);
  1044. this.onPointerObservable.notifyObservers(pi, type);
  1045. }
  1046. }
  1047. return this;
  1048. }
  1049. /**
  1050. * Use this method to simulate a pointer up on a mesh
  1051. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1052. */
  1053. public simulatePointerUp(pickResult: PickingInfo): Scene {
  1054. let evt = new PointerEvent("pointerup");
  1055. let clickInfo = new ClickInfo();
  1056. clickInfo.singleClick = true;
  1057. return this._processPointerUp(pickResult, evt, clickInfo);
  1058. }
  1059. private _processPointerUp(pickResult: Nullable<PickingInfo>, evt: PointerEvent, clickInfo: ClickInfo): Scene {
  1060. if (pickResult && pickResult && pickResult.pickedMesh) {
  1061. this._pickedUpMesh = pickResult.pickedMesh;
  1062. if (this._pickedDownMesh === this._pickedUpMesh) {
  1063. if (this.onPointerPick) {
  1064. this.onPointerPick(evt, pickResult);
  1065. }
  1066. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  1067. let type = PointerEventTypes.POINTERPICK;
  1068. let pi = new PointerInfo(type, evt, pickResult);
  1069. this.onPointerObservable.notifyObservers(pi, type);
  1070. }
  1071. }
  1072. if (pickResult.pickedMesh.actionManager) {
  1073. if (clickInfo.ignore) {
  1074. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1075. }
  1076. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  1077. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1078. }
  1079. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1080. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1081. }
  1082. }
  1083. }
  1084. if (this._pickedDownMesh &&
  1085. this._pickedDownMesh.actionManager &&
  1086. this._pickedDownMesh.actionManager.hasSpecificTrigger(ActionManager.OnPickOutTrigger) &&
  1087. this._pickedDownMesh !== this._pickedUpMesh) {
  1088. this._pickedDownMesh.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  1089. }
  1090. if (this.onPointerUp) {
  1091. this.onPointerUp(evt, pickResult);
  1092. }
  1093. if (this.onPointerObservable.hasObservers()) {
  1094. if (!clickInfo.ignore) {
  1095. if (!clickInfo.hasSwiped) {
  1096. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1097. let type = PointerEventTypes.POINTERTAP;
  1098. let pi = new PointerInfo(type, evt, pickResult);
  1099. this.onPointerObservable.notifyObservers(pi, type);
  1100. }
  1101. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1102. let type = PointerEventTypes.POINTERDOUBLETAP;
  1103. let pi = new PointerInfo(type, evt, pickResult);
  1104. this.onPointerObservable.notifyObservers(pi, type);
  1105. }
  1106. }
  1107. }
  1108. else {
  1109. let type = PointerEventTypes.POINTERUP;
  1110. let pi = new PointerInfo(type, evt, pickResult);
  1111. this.onPointerObservable.notifyObservers(pi, type);
  1112. }
  1113. }
  1114. return this;
  1115. }
  1116. /**
  1117. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1118. * @param attachUp defines if you want to attach events to pointerup
  1119. * @param attachDown defines if you want to attach events to pointerdown
  1120. * @param attachMove defines if you want to attach events to pointermove
  1121. */
  1122. public attachControl(attachUp = true, attachDown = true, attachMove = true) {
  1123. this._initActionManager = (act: Nullable<ActionManager>, clickInfo: ClickInfo): Nullable<ActionManager> => {
  1124. if (!this._meshPickProceed) {
  1125. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1126. this._currentPickResult = pickResult;
  1127. if (pickResult) {
  1128. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  1129. }
  1130. this._meshPickProceed = true;
  1131. }
  1132. return act;
  1133. };
  1134. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void) => {
  1135. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  1136. if ((new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  1137. btn !== this._previousButtonPressed) {
  1138. this._doubleClickOccured = false;
  1139. clickInfo.singleClick = true;
  1140. clickInfo.ignore = false;
  1141. cb(clickInfo, this._currentPickResult);
  1142. }
  1143. }
  1144. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => void): void => {
  1145. let clickInfo = new ClickInfo();
  1146. this._currentPickResult = null;
  1147. let act: Nullable<ActionManager> = null;
  1148. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  1149. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  1150. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1151. if (!checkPicking && BABYLON.ActionManager && ActionManager.HasPickTriggers) {
  1152. act = this._initActionManager(act, clickInfo);
  1153. if (act)
  1154. checkPicking = act.hasPickTriggers;
  1155. }
  1156. if (checkPicking) {
  1157. let btn = evt.button;
  1158. clickInfo.hasSwiped = Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  1159. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  1160. if (!clickInfo.hasSwiped) {
  1161. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  1162. if (!checkSingleClickImmediately) {
  1163. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  1164. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1165. if (checkSingleClickImmediately && !ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1166. act = this._initActionManager(act, clickInfo);
  1167. if (act)
  1168. checkSingleClickImmediately = !act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1169. }
  1170. }
  1171. if (checkSingleClickImmediately) {
  1172. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  1173. if (new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  1174. btn !== this._previousButtonPressed) {
  1175. clickInfo.singleClick = true;
  1176. cb(clickInfo, this._currentPickResult);
  1177. }
  1178. }
  1179. // at least one double click is required to be check and exclusive double click is enabled
  1180. else {
  1181. // wait that no double click has been raised during the double click delay
  1182. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1183. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  1184. }
  1185. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  1186. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  1187. if (!checkDoubleClick && ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1188. act = this._initActionManager(act, clickInfo);
  1189. if (act)
  1190. checkDoubleClick = act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  1191. }
  1192. if (checkDoubleClick) {
  1193. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  1194. if (btn === this._previousButtonPressed &&
  1195. new Date().getTime() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  1196. !this._doubleClickOccured
  1197. ) {
  1198. // pointer has not moved for 2 clicks, it's a double click
  1199. if (!clickInfo.hasSwiped &&
  1200. Math.abs(this._previousStartingPointerPosition.x - this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  1201. Math.abs(this._previousStartingPointerPosition.y - this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  1202. this._previousStartingPointerTime = 0;
  1203. this._doubleClickOccured = true;
  1204. clickInfo.doubleClick = true;
  1205. clickInfo.ignore = false;
  1206. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout) {
  1207. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1208. }
  1209. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1210. cb(clickInfo, this._currentPickResult);
  1211. }
  1212. // if the two successive clicks are too far, it's just two simple clicks
  1213. else {
  1214. this._doubleClickOccured = false;
  1215. this._previousStartingPointerTime = this._startingPointerTime;
  1216. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1217. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1218. this._previousButtonPressed = btn;
  1219. this._previousHasSwiped = clickInfo.hasSwiped;
  1220. if (Scene.ExclusiveDoubleClickMode) {
  1221. if (this._previousDelayedSimpleClickTimeout) {
  1222. clearTimeout(this._previousDelayedSimpleClickTimeout);
  1223. }
  1224. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  1225. cb(clickInfo, this._previousPickResult);
  1226. }
  1227. else {
  1228. cb(clickInfo, this._currentPickResult);
  1229. }
  1230. }
  1231. }
  1232. // just the first click of the double has been raised
  1233. else {
  1234. this._doubleClickOccured = false;
  1235. this._previousStartingPointerTime = this._startingPointerTime;
  1236. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  1237. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  1238. this._previousButtonPressed = btn;
  1239. this._previousHasSwiped = clickInfo.hasSwiped;
  1240. }
  1241. }
  1242. }
  1243. }
  1244. clickInfo.ignore = true;
  1245. cb(clickInfo, this._currentPickResult);
  1246. };
  1247. this._spritePredicate = (sprite: Sprite): boolean => {
  1248. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  1249. };
  1250. this._onPointerMove = (evt: PointerEvent) => {
  1251. this._updatePointerPosition(evt);
  1252. // PreObservable support
  1253. if (this.onPrePointerObservable.hasObservers()) {
  1254. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  1255. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1256. this.onPrePointerObservable.notifyObservers(pi, type);
  1257. if (pi.skipOnPointerObservable) {
  1258. return;
  1259. }
  1260. }
  1261. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1262. return;
  1263. }
  1264. if (!this.pointerMovePredicate) {
  1265. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined));
  1266. }
  1267. // Meshes
  1268. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  1269. this._processPointerMove(pickResult, evt);
  1270. };
  1271. this._onPointerDown = (evt: PointerEvent) => {
  1272. this._totalPointersPressed++;
  1273. this._pickedDownMesh = null;
  1274. this._meshPickProceed = false;
  1275. this._updatePointerPosition(evt);
  1276. if (this.preventDefaultOnPointerDown && canvas) {
  1277. evt.preventDefault();
  1278. canvas.focus();
  1279. }
  1280. // PreObservable support
  1281. if (this.onPrePointerObservable.hasObservers()) {
  1282. let type = PointerEventTypes.POINTERDOWN;
  1283. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1284. this.onPrePointerObservable.notifyObservers(pi, type);
  1285. if (pi.skipOnPointerObservable) {
  1286. return;
  1287. }
  1288. }
  1289. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1290. return;
  1291. }
  1292. this._startingPointerPosition.x = this._pointerX;
  1293. this._startingPointerPosition.y = this._pointerY;
  1294. this._startingPointerTime = new Date().getTime();
  1295. if (!this.pointerDownPredicate) {
  1296. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  1297. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1298. };
  1299. }
  1300. // Meshes
  1301. this._pickedDownMesh = null;
  1302. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  1303. this._processPointerDown(pickResult, evt);
  1304. // Sprites
  1305. this._pickedDownSprite = null;
  1306. if (this.spriteManagers.length > 0) {
  1307. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1308. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  1309. if (pickResult.pickedSprite.actionManager) {
  1310. this._pickedDownSprite = pickResult.pickedSprite;
  1311. switch (evt.button) {
  1312. case 0:
  1313. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1314. break;
  1315. case 1:
  1316. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1317. break;
  1318. case 2:
  1319. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1320. break;
  1321. }
  1322. if (pickResult.pickedSprite.actionManager) {
  1323. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1324. }
  1325. }
  1326. }
  1327. }
  1328. };
  1329. this._onPointerUp = (evt: PointerEvent) => {
  1330. if (this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  1331. return; // So we need to test it the pointer down was pressed before.
  1332. }
  1333. this._totalPointersPressed--;
  1334. this._pickedUpMesh = null;
  1335. this._meshPickProceed = false;
  1336. this._updatePointerPosition(evt);
  1337. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (clickInfo: ClickInfo, pickResult: Nullable<PickingInfo>) => {
  1338. // PreObservable support
  1339. if (this.onPrePointerObservable.hasObservers()) {
  1340. if (!clickInfo.ignore) {
  1341. if (!clickInfo.hasSwiped) {
  1342. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1343. let type = PointerEventTypes.POINTERTAP;
  1344. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1345. this.onPrePointerObservable.notifyObservers(pi, type);
  1346. if (pi.skipOnPointerObservable) {
  1347. return;
  1348. }
  1349. }
  1350. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1351. let type = PointerEventTypes.POINTERDOUBLETAP;
  1352. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1353. this.onPrePointerObservable.notifyObservers(pi, type);
  1354. if (pi.skipOnPointerObservable) {
  1355. return;
  1356. }
  1357. }
  1358. }
  1359. }
  1360. else {
  1361. let type = PointerEventTypes.POINTERUP;
  1362. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1363. this.onPrePointerObservable.notifyObservers(pi, type);
  1364. if (pi.skipOnPointerObservable) {
  1365. return;
  1366. }
  1367. }
  1368. }
  1369. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1370. return;
  1371. }
  1372. if (!this.pointerUpPredicate) {
  1373. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1374. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  1375. };
  1376. }
  1377. // Meshes
  1378. if (!this._meshPickProceed && (BABYLON.ActionManager && ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1379. this._initActionManager(null, clickInfo);
  1380. }
  1381. if (!pickResult) {
  1382. pickResult = this._currentPickResult;
  1383. }
  1384. this._processPointerUp(pickResult, evt, clickInfo);
  1385. // Sprites
  1386. if (this.spriteManagers.length > 0) {
  1387. let spritePickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  1388. if (spritePickResult) {
  1389. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  1390. if (spritePickResult.pickedSprite.actionManager) {
  1391. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1392. if (spritePickResult.pickedSprite.actionManager) {
  1393. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  1394. spritePickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, this, evt));
  1395. }
  1396. }
  1397. }
  1398. }
  1399. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== spritePickResult.pickedSprite) {
  1400. this._pickedDownSprite.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  1401. }
  1402. }
  1403. }
  1404. this._previousPickResult = this._currentPickResult;
  1405. });
  1406. };
  1407. this._onKeyDown = (evt: KeyboardEvent) => {
  1408. let type = KeyboardEventTypes.KEYDOWN;
  1409. if (this.onPreKeyboardObservable.hasObservers()) {
  1410. let pi = new KeyboardInfoPre(type, evt);
  1411. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1412. if (pi.skipOnPointerObservable) {
  1413. return;
  1414. }
  1415. }
  1416. if (this.onKeyboardObservable.hasObservers()) {
  1417. let pi = new KeyboardInfo(type, evt);
  1418. this.onKeyboardObservable.notifyObservers(pi, type);
  1419. }
  1420. if (this.actionManager) {
  1421. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1422. }
  1423. };
  1424. this._onKeyUp = (evt: KeyboardEvent) => {
  1425. let type = KeyboardEventTypes.KEYUP;
  1426. if (this.onPreKeyboardObservable.hasObservers()) {
  1427. let pi = new KeyboardInfoPre(type, evt);
  1428. this.onPreKeyboardObservable.notifyObservers(pi, type);
  1429. if (pi.skipOnPointerObservable) {
  1430. return;
  1431. }
  1432. }
  1433. if (this.onKeyboardObservable.hasObservers()) {
  1434. let pi = new KeyboardInfo(type, evt);
  1435. this.onKeyboardObservable.notifyObservers(pi, type);
  1436. }
  1437. if (this.actionManager) {
  1438. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1439. }
  1440. };
  1441. let engine = this.getEngine();
  1442. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(()=>{
  1443. if (!canvas) {
  1444. return;
  1445. }
  1446. canvas.addEventListener("keydown", this._onKeyDown, false);
  1447. canvas.addEventListener("keyup", this._onKeyUp, false);
  1448. });
  1449. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(()=>{
  1450. if (!canvas) {
  1451. return;
  1452. }
  1453. canvas.removeEventListener("keydown", this._onKeyDown);
  1454. canvas.removeEventListener("keyup", this._onKeyUp);
  1455. });
  1456. var eventPrefix = Tools.GetPointerPrefix();
  1457. var canvas = this._engine.getRenderingCanvas();
  1458. if (!canvas) {
  1459. return;
  1460. }
  1461. if (attachMove) {
  1462. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  1463. // Wheel
  1464. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  1465. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  1466. }
  1467. if (attachDown) {
  1468. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  1469. }
  1470. if (attachUp) {
  1471. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  1472. }
  1473. canvas.tabIndex = 1;
  1474. }
  1475. public detachControl() {
  1476. let engine = this.getEngine();
  1477. var eventPrefix = Tools.GetPointerPrefix();
  1478. var canvas = engine.getRenderingCanvas();
  1479. if (!canvas) {
  1480. return;
  1481. }
  1482. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  1483. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  1484. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  1485. if (this._onCanvasBlurObserver) {
  1486. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  1487. }
  1488. if (this._onCanvasFocusObserver) {
  1489. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  1490. }
  1491. // Wheel
  1492. canvas.removeEventListener('mousewheel', this._onPointerMove);
  1493. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  1494. // Keyboard
  1495. canvas.removeEventListener("keydown", this._onKeyDown);
  1496. canvas.removeEventListener("keyup", this._onKeyUp);
  1497. // Observables
  1498. this.onKeyboardObservable.clear();
  1499. this.onPreKeyboardObservable.clear();
  1500. this.onPointerObservable.clear();
  1501. this.onPrePointerObservable.clear();
  1502. }
  1503. // Ready
  1504. public isReady(): boolean {
  1505. if (this._isDisposed) {
  1506. return false;
  1507. }
  1508. if (this._pendingData.length > 0) {
  1509. return false;
  1510. }
  1511. var index: number;
  1512. // Geometries
  1513. for (index = 0; index < this._geometries.length; index++) {
  1514. var geometry = this._geometries[index];
  1515. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1516. return false;
  1517. }
  1518. }
  1519. // Meshes
  1520. for (index = 0; index < this.meshes.length; index++) {
  1521. var mesh = this.meshes[index];
  1522. if (!mesh.isEnabled()) {
  1523. continue;
  1524. }
  1525. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  1526. continue;
  1527. }
  1528. if (!mesh.isReady()) {
  1529. return false;
  1530. }
  1531. var mat = mesh.material;
  1532. if (mat) {
  1533. if (!mat.isReady(mesh)) {
  1534. return false;
  1535. }
  1536. }
  1537. }
  1538. return true;
  1539. }
  1540. public resetCachedMaterial(): void {
  1541. this._cachedMaterial = null;
  1542. this._cachedEffect = null;
  1543. this._cachedVisibility = null;
  1544. }
  1545. public registerBeforeRender(func: () => void): void {
  1546. this.onBeforeRenderObservable.add(func);
  1547. }
  1548. public unregisterBeforeRender(func: () => void): void {
  1549. this.onBeforeRenderObservable.removeCallback(func);
  1550. }
  1551. public registerAfterRender(func: () => void): void {
  1552. this.onAfterRenderObservable.add(func);
  1553. }
  1554. public unregisterAfterRender(func: () => void): void {
  1555. this.onAfterRenderObservable.removeCallback(func);
  1556. }
  1557. public _addPendingData(data: any): void {
  1558. this._pendingData.push(data);
  1559. }
  1560. public _removePendingData(data: any): void {
  1561. var index = this._pendingData.indexOf(data);
  1562. if (index !== -1) {
  1563. this._pendingData.splice(index, 1);
  1564. }
  1565. }
  1566. public getWaitingItemsCount(): number {
  1567. return this._pendingData.length;
  1568. }
  1569. /**
  1570. * Registers a function to be executed when the scene is ready.
  1571. * @param {Function} func - the function to be executed.
  1572. */
  1573. public executeWhenReady(func: () => void): void {
  1574. this.onReadyObservable.add(func);
  1575. if (this._executeWhenReadyTimeoutId !== -1) {
  1576. return;
  1577. }
  1578. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1579. this._checkIsReady();
  1580. }, 150);
  1581. }
  1582. public _checkIsReady() {
  1583. if (this.isReady()) {
  1584. this.onReadyObservable.notifyObservers(this);
  1585. this.onReadyObservable.clear();
  1586. this._executeWhenReadyTimeoutId = -1;
  1587. return;
  1588. }
  1589. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1590. this._checkIsReady();
  1591. }, 150);
  1592. }
  1593. // Animations
  1594. /**
  1595. * Will start the animation sequence of a given target
  1596. * @param target - the target
  1597. * @param {number} from - from which frame should animation start
  1598. * @param {number} to - till which frame should animation run.
  1599. * @param {boolean} [loop] - should the animation loop
  1600. * @param {number} [speedRatio] - the speed in which to run the animation
  1601. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  1602. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  1603. * Returns {BABYLON.Animatable} the animatable object created for this animation
  1604. * See BABYLON.Animatable
  1605. */
  1606. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  1607. if (from > to && speedRatio > 0) {
  1608. speedRatio *= -1;
  1609. }
  1610. this.stopAnimation(target);
  1611. if (!animatable) {
  1612. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  1613. }
  1614. // Local animations
  1615. if (target.animations) {
  1616. animatable.appendAnimations(target, target.animations);
  1617. }
  1618. // Children animations
  1619. if (target.getAnimatables) {
  1620. var animatables = target.getAnimatables();
  1621. for (var index = 0; index < animatables.length; index++) {
  1622. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  1623. }
  1624. }
  1625. animatable.reset();
  1626. return animatable;
  1627. }
  1628. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  1629. if (speedRatio === undefined) {
  1630. speedRatio = 1.0;
  1631. }
  1632. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  1633. return animatable;
  1634. }
  1635. public getAnimatableByTarget(target: any): Nullable<Animatable> {
  1636. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1637. if (this._activeAnimatables[index].target === target) {
  1638. return this._activeAnimatables[index];
  1639. }
  1640. }
  1641. return null;
  1642. }
  1643. public get Animatables(): Animatable[] {
  1644. return this._activeAnimatables;
  1645. }
  1646. /**
  1647. * Will stop the animation of the given target
  1648. * @param target - the target
  1649. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  1650. * @see beginAnimation
  1651. */
  1652. public stopAnimation(target: any, animationName?: string): void {
  1653. var animatable = this.getAnimatableByTarget(target);
  1654. if (animatable) {
  1655. animatable.stop(animationName);
  1656. }
  1657. }
  1658. private _animate(): void {
  1659. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  1660. return;
  1661. }
  1662. // Getting time
  1663. var now = Tools.Now;
  1664. if (!this._animationTimeLast) {
  1665. if (this._pendingData.length > 0) {
  1666. return;
  1667. }
  1668. this._animationTimeLast = now;
  1669. }
  1670. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  1671. this._animationTime += deltaTime;
  1672. this._animationTimeLast = now;
  1673. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1674. this._activeAnimatables[index]._animate(this._animationTime);
  1675. }
  1676. }
  1677. // Matrix
  1678. public _switchToAlternateCameraConfiguration(active: boolean): void {
  1679. this._useAlternateCameraConfiguration = active;
  1680. }
  1681. public getViewMatrix(): Matrix {
  1682. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  1683. }
  1684. public getProjectionMatrix(): Matrix {
  1685. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  1686. }
  1687. public getTransformMatrix(): Matrix {
  1688. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  1689. }
  1690. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  1691. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  1692. return;
  1693. }
  1694. this._viewUpdateFlag = view.updateFlag;
  1695. this._projectionUpdateFlag = projection.updateFlag;
  1696. this._viewMatrix = view;
  1697. this._projectionMatrix = projection;
  1698. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  1699. // Update frustum
  1700. if (!this._frustumPlanes) {
  1701. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  1702. } else {
  1703. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1704. }
  1705. if (this.activeCamera && this.activeCamera._alternateCamera) {
  1706. let otherCamera = this.activeCamera._alternateCamera;
  1707. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), Tmp.Matrix[0]);
  1708. Frustum.GetRightPlaneToRef(Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  1709. }
  1710. if (this._sceneUbo.useUbo) {
  1711. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  1712. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  1713. this._sceneUbo.update();
  1714. }
  1715. }
  1716. public _setAlternateTransformMatrix(view: Matrix, projection: Matrix): void {
  1717. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  1718. return;
  1719. }
  1720. this._alternateViewUpdateFlag = view.updateFlag;
  1721. this._alternateProjectionUpdateFlag = projection.updateFlag;
  1722. this._alternateViewMatrix = view;
  1723. this._alternateProjectionMatrix = projection;
  1724. if (!this._alternateTransformMatrix) {
  1725. this._alternateTransformMatrix = Matrix.Zero();
  1726. }
  1727. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  1728. if (!this._alternateSceneUbo) {
  1729. this._createAlternateUbo();
  1730. }
  1731. if (this._alternateSceneUbo.useUbo) {
  1732. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  1733. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  1734. this._alternateSceneUbo.update();
  1735. }
  1736. }
  1737. public getSceneUniformBuffer(): UniformBuffer {
  1738. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  1739. }
  1740. // Methods
  1741. public getUniqueId() {
  1742. var result = Scene._uniqueIdCounter;
  1743. Scene._uniqueIdCounter++;
  1744. return result;
  1745. }
  1746. public addMesh(newMesh: AbstractMesh) {
  1747. this.meshes.push(newMesh);
  1748. //notify the collision coordinator
  1749. if (this.collisionCoordinator) {
  1750. this.collisionCoordinator.onMeshAdded(newMesh);
  1751. }
  1752. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  1753. }
  1754. public removeMesh(toRemove: AbstractMesh): number {
  1755. var index = this.meshes.indexOf(toRemove);
  1756. if (index !== -1) {
  1757. // Remove from the scene if mesh found
  1758. this.meshes.splice(index, 1);
  1759. }
  1760. //notify the collision coordinator
  1761. if (this.collisionCoordinator) {
  1762. this.collisionCoordinator.onMeshRemoved(toRemove);
  1763. }
  1764. this.onMeshRemovedObservable.notifyObservers(toRemove);
  1765. return index;
  1766. }
  1767. public removeSkeleton(toRemove: Skeleton): number {
  1768. var index = this.skeletons.indexOf(toRemove);
  1769. if (index !== -1) {
  1770. // Remove from the scene if found
  1771. this.skeletons.splice(index, 1);
  1772. }
  1773. return index;
  1774. }
  1775. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  1776. var index = this.morphTargetManagers.indexOf(toRemove);
  1777. if (index !== -1) {
  1778. // Remove from the scene if found
  1779. this.morphTargetManagers.splice(index, 1);
  1780. }
  1781. return index;
  1782. }
  1783. public removeLight(toRemove: Light): number {
  1784. var index = this.lights.indexOf(toRemove);
  1785. if (index !== -1) {
  1786. // Remove from the scene if mesh found
  1787. this.lights.splice(index, 1);
  1788. this.sortLightsByPriority();
  1789. }
  1790. this.onLightRemovedObservable.notifyObservers(toRemove);
  1791. return index;
  1792. }
  1793. public removeCamera(toRemove: Camera): number {
  1794. var index = this.cameras.indexOf(toRemove);
  1795. if (index !== -1) {
  1796. // Remove from the scene if mesh found
  1797. this.cameras.splice(index, 1);
  1798. }
  1799. // Remove from activeCameras
  1800. var index2 = this.activeCameras.indexOf(toRemove);
  1801. if (index2 !== -1) {
  1802. // Remove from the scene if mesh found
  1803. this.activeCameras.splice(index2, 1);
  1804. }
  1805. // Reset the activeCamera
  1806. if (this.activeCamera === toRemove) {
  1807. if (this.cameras.length > 0) {
  1808. this.activeCamera = this.cameras[0];
  1809. } else {
  1810. this.activeCamera = null;
  1811. }
  1812. }
  1813. this.onCameraRemovedObservable.notifyObservers(toRemove);
  1814. return index;
  1815. }
  1816. public addLight(newLight: Light) {
  1817. this.lights.push(newLight);
  1818. this.sortLightsByPriority();
  1819. this.onNewLightAddedObservable.notifyObservers(newLight);
  1820. }
  1821. public sortLightsByPriority(): void {
  1822. if (this.requireLightSorting) {
  1823. this.lights.sort(Light.compareLightsPriority);
  1824. }
  1825. }
  1826. public addCamera(newCamera: Camera) {
  1827. this.cameras.push(newCamera);
  1828. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  1829. }
  1830. /**
  1831. * Switch active camera
  1832. * @param {Camera} newCamera - new active camera
  1833. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  1834. */
  1835. public switchActiveCamera(newCamera: Camera, attachControl = true) {
  1836. var canvas = this._engine.getRenderingCanvas();
  1837. if (!canvas) {
  1838. return;
  1839. }
  1840. if (this.activeCamera) {
  1841. this.activeCamera.detachControl(canvas);
  1842. }
  1843. this.activeCamera = newCamera;
  1844. if (attachControl) {
  1845. newCamera.attachControl(canvas);
  1846. }
  1847. }
  1848. /**
  1849. * sets the active camera of the scene using its ID
  1850. * @param {string} id - the camera's ID
  1851. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  1852. * @see activeCamera
  1853. */
  1854. public setActiveCameraByID(id: string): Nullable<Camera> {
  1855. var camera = this.getCameraByID(id);
  1856. if (camera) {
  1857. this.activeCamera = camera;
  1858. return camera;
  1859. }
  1860. return null;
  1861. }
  1862. /**
  1863. * sets the active camera of the scene using its name
  1864. * @param {string} name - the camera's name
  1865. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  1866. * @see activeCamera
  1867. */
  1868. public setActiveCameraByName(name: string): Nullable<Camera> {
  1869. var camera = this.getCameraByName(name);
  1870. if (camera) {
  1871. this.activeCamera = camera;
  1872. return camera;
  1873. }
  1874. return null;
  1875. }
  1876. /**
  1877. * get a material using its id
  1878. * @param {string} the material's ID
  1879. * @return {BABYLON.Material|null} the material or null if none found.
  1880. */
  1881. public getMaterialByID(id: string): Nullable<Material> {
  1882. for (var index = 0; index < this.materials.length; index++) {
  1883. if (this.materials[index].id === id) {
  1884. return this.materials[index];
  1885. }
  1886. }
  1887. return null;
  1888. }
  1889. /**
  1890. * get a material using its name
  1891. * @param {string} the material's name
  1892. * @return {BABYLON.Material|null} the material or null if none found.
  1893. */
  1894. public getMaterialByName(name: string): Nullable<Material> {
  1895. for (var index = 0; index < this.materials.length; index++) {
  1896. if (this.materials[index].name === name) {
  1897. return this.materials[index];
  1898. }
  1899. }
  1900. return null;
  1901. }
  1902. public getLensFlareSystemByName(name: string): Nullable<LensFlareSystem> {
  1903. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  1904. if (this.lensFlareSystems[index].name === name) {
  1905. return this.lensFlareSystems[index];
  1906. }
  1907. }
  1908. return null;
  1909. }
  1910. public getLensFlareSystemByID(id: string): Nullable<LensFlareSystem> {
  1911. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  1912. if (this.lensFlareSystems[index].id === id) {
  1913. return this.lensFlareSystems[index];
  1914. }
  1915. }
  1916. return null;
  1917. }
  1918. public getCameraByID(id: string): Nullable<Camera> {
  1919. for (var index = 0; index < this.cameras.length; index++) {
  1920. if (this.cameras[index].id === id) {
  1921. return this.cameras[index];
  1922. }
  1923. }
  1924. return null;
  1925. }
  1926. public getCameraByUniqueID(uniqueId: number): Nullable<Camera> {
  1927. for (var index = 0; index < this.cameras.length; index++) {
  1928. if (this.cameras[index].uniqueId === uniqueId) {
  1929. return this.cameras[index];
  1930. }
  1931. }
  1932. return null;
  1933. }
  1934. /**
  1935. * get a camera using its name
  1936. * @param {string} the camera's name
  1937. * @return {BABYLON.Camera|null} the camera or null if none found.
  1938. */
  1939. public getCameraByName(name: string): Nullable<Camera> {
  1940. for (var index = 0; index < this.cameras.length; index++) {
  1941. if (this.cameras[index].name === name) {
  1942. return this.cameras[index];
  1943. }
  1944. }
  1945. return null;
  1946. }
  1947. /**
  1948. * get a bone using its id
  1949. * @param {string} the bone's id
  1950. * @return {BABYLON.Bone|null} the bone or null if not found
  1951. */
  1952. public getBoneByID(id: string): Nullable<Bone> {
  1953. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  1954. var skeleton = this.skeletons[skeletonIndex];
  1955. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  1956. if (skeleton.bones[boneIndex].id === id) {
  1957. return skeleton.bones[boneIndex];
  1958. }
  1959. }
  1960. }
  1961. return null;
  1962. }
  1963. /**
  1964. * get a bone using its id
  1965. * @param {string} the bone's name
  1966. * @return {BABYLON.Bone|null} the bone or null if not found
  1967. */
  1968. public getBoneByName(name: string): Nullable<Bone> {
  1969. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  1970. var skeleton = this.skeletons[skeletonIndex];
  1971. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  1972. if (skeleton.bones[boneIndex].name === name) {
  1973. return skeleton.bones[boneIndex];
  1974. }
  1975. }
  1976. }
  1977. return null;
  1978. }
  1979. /**
  1980. * get a light node using its name
  1981. * @param {string} the light's name
  1982. * @return {BABYLON.Light|null} the light or null if none found.
  1983. */
  1984. public getLightByName(name: string): Nullable<Light> {
  1985. for (var index = 0; index < this.lights.length; index++) {
  1986. if (this.lights[index].name === name) {
  1987. return this.lights[index];
  1988. }
  1989. }
  1990. return null;
  1991. }
  1992. /**
  1993. * get a light node using its ID
  1994. * @param {string} the light's id
  1995. * @return {BABYLON.Light|null} the light or null if none found.
  1996. */
  1997. public getLightByID(id: string): Nullable<Light> {
  1998. for (var index = 0; index < this.lights.length; index++) {
  1999. if (this.lights[index].id === id) {
  2000. return this.lights[index];
  2001. }
  2002. }
  2003. return null;
  2004. }
  2005. /**
  2006. * get a light node using its scene-generated unique ID
  2007. * @param {number} the light's unique id
  2008. * @return {BABYLON.Light|null} the light or null if none found.
  2009. */
  2010. public getLightByUniqueID(uniqueId: number): Nullable<Light> {
  2011. for (var index = 0; index < this.lights.length; index++) {
  2012. if (this.lights[index].uniqueId === uniqueId) {
  2013. return this.lights[index];
  2014. }
  2015. }
  2016. return null;
  2017. }
  2018. /**
  2019. * get a particle system by id
  2020. * @param id {number} the particle system id
  2021. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  2022. */
  2023. public getParticleSystemByID(id: string): Nullable<IParticleSystem> {
  2024. for (var index = 0; index < this.particleSystems.length; index++) {
  2025. if (this.particleSystems[index].id === id) {
  2026. return this.particleSystems[index];
  2027. }
  2028. }
  2029. return null;
  2030. }
  2031. /**
  2032. * get a geometry using its ID
  2033. * @param {string} the geometry's id
  2034. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  2035. */
  2036. public getGeometryByID(id: string): Nullable<Geometry> {
  2037. for (var index = 0; index < this._geometries.length; index++) {
  2038. if (this._geometries[index].id === id) {
  2039. return this._geometries[index];
  2040. }
  2041. }
  2042. return null;
  2043. }
  2044. /**
  2045. * add a new geometry to this scene.
  2046. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  2047. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  2048. * @return {boolean} was the geometry added or not
  2049. */
  2050. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  2051. if (!force && this.getGeometryByID(geometry.id)) {
  2052. return false;
  2053. }
  2054. this._geometries.push(geometry);
  2055. //notify the collision coordinator
  2056. if (this.collisionCoordinator) {
  2057. this.collisionCoordinator.onGeometryAdded(geometry);
  2058. }
  2059. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  2060. return true;
  2061. }
  2062. /**
  2063. * Removes an existing geometry
  2064. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  2065. * @return {boolean} was the geometry removed or not
  2066. */
  2067. public removeGeometry(geometry: Geometry): boolean {
  2068. var index = this._geometries.indexOf(geometry);
  2069. if (index > -1) {
  2070. this._geometries.splice(index, 1);
  2071. //notify the collision coordinator
  2072. if (this.collisionCoordinator) {
  2073. this.collisionCoordinator.onGeometryDeleted(geometry);
  2074. }
  2075. this.onGeometryRemovedObservable.notifyObservers(geometry);
  2076. return true;
  2077. }
  2078. return false;
  2079. }
  2080. public getGeometries(): Geometry[] {
  2081. return this._geometries;
  2082. }
  2083. /**
  2084. * Get the first added mesh found of a given ID
  2085. * @param {string} id - the id to search for
  2086. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2087. */
  2088. public getMeshByID(id: string): Nullable<AbstractMesh> {
  2089. for (var index = 0; index < this.meshes.length; index++) {
  2090. if (this.meshes[index].id === id) {
  2091. return this.meshes[index];
  2092. }
  2093. }
  2094. return null;
  2095. }
  2096. public getMeshesByID(id: string): Array<AbstractMesh> {
  2097. return this.meshes.filter(function (m) {
  2098. return m.id === id;
  2099. })
  2100. }
  2101. /**
  2102. * Get a mesh with its auto-generated unique id
  2103. * @param {number} uniqueId - the unique id to search for
  2104. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2105. */
  2106. public getMeshByUniqueID(uniqueId: number): Nullable<AbstractMesh> {
  2107. for (var index = 0; index < this.meshes.length; index++) {
  2108. if (this.meshes[index].uniqueId === uniqueId) {
  2109. return this.meshes[index];
  2110. }
  2111. }
  2112. return null;
  2113. }
  2114. /**
  2115. * Get a the last added mesh found of a given ID
  2116. * @param {string} id - the id to search for
  2117. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  2118. */
  2119. public getLastMeshByID(id: string): Nullable<AbstractMesh> {
  2120. for (var index = this.meshes.length - 1; index >= 0; index--) {
  2121. if (this.meshes[index].id === id) {
  2122. return this.meshes[index];
  2123. }
  2124. }
  2125. return null;
  2126. }
  2127. /**
  2128. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  2129. * @param {string} id - the id to search for
  2130. * @return {BABYLON.Node|null} the node found or null if not found at all.
  2131. */
  2132. public getLastEntryByID(id: string): Nullable<Node> {
  2133. var index: number;
  2134. for (index = this.meshes.length - 1; index >= 0; index--) {
  2135. if (this.meshes[index].id === id) {
  2136. return this.meshes[index];
  2137. }
  2138. }
  2139. for (index = this.cameras.length - 1; index >= 0; index--) {
  2140. if (this.cameras[index].id === id) {
  2141. return this.cameras[index];
  2142. }
  2143. }
  2144. for (index = this.lights.length - 1; index >= 0; index--) {
  2145. if (this.lights[index].id === id) {
  2146. return this.lights[index];
  2147. }
  2148. }
  2149. return null;
  2150. }
  2151. public getNodeByID(id: string): Nullable<Node> {
  2152. var mesh = this.getMeshByID(id);
  2153. if (mesh) {
  2154. return mesh;
  2155. }
  2156. var light = this.getLightByID(id);
  2157. if (light) {
  2158. return light;
  2159. }
  2160. var camera = this.getCameraByID(id);
  2161. if (camera) {
  2162. return camera;
  2163. }
  2164. var bone = this.getBoneByID(id);
  2165. return bone;
  2166. }
  2167. public getNodeByName(name: string): Nullable<Node> {
  2168. var mesh = this.getMeshByName(name);
  2169. if (mesh) {
  2170. return mesh;
  2171. }
  2172. var light = this.getLightByName(name);
  2173. if (light) {
  2174. return light;
  2175. }
  2176. var camera = this.getCameraByName(name);
  2177. if (camera) {
  2178. return camera;
  2179. }
  2180. var bone = this.getBoneByName(name);
  2181. return bone;
  2182. }
  2183. public getMeshByName(name: string): Nullable<AbstractMesh> {
  2184. for (var index = 0; index < this.meshes.length; index++) {
  2185. if (this.meshes[index].name === name) {
  2186. return this.meshes[index];
  2187. }
  2188. }
  2189. return null;
  2190. }
  2191. public getSoundByName(name: string): Nullable<Sound> {
  2192. var index: number;
  2193. if (AudioEngine) {
  2194. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  2195. if (this.mainSoundTrack.soundCollection[index].name === name) {
  2196. return this.mainSoundTrack.soundCollection[index];
  2197. }
  2198. }
  2199. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  2200. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  2201. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  2202. return this.soundTracks[sdIndex].soundCollection[index];
  2203. }
  2204. }
  2205. }
  2206. }
  2207. return null;
  2208. }
  2209. public getLastSkeletonByID(id: string): Nullable<Skeleton> {
  2210. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  2211. if (this.skeletons[index].id === id) {
  2212. return this.skeletons[index];
  2213. }
  2214. }
  2215. return null;
  2216. }
  2217. public getSkeletonById(id: string): Nullable<Skeleton> {
  2218. for (var index = 0; index < this.skeletons.length; index++) {
  2219. if (this.skeletons[index].id === id) {
  2220. return this.skeletons[index];
  2221. }
  2222. }
  2223. return null;
  2224. }
  2225. public getSkeletonByName(name: string): Nullable<Skeleton> {
  2226. for (var index = 0; index < this.skeletons.length; index++) {
  2227. if (this.skeletons[index].name === name) {
  2228. return this.skeletons[index];
  2229. }
  2230. }
  2231. return null;
  2232. }
  2233. public getMorphTargetManagerById(id: number): Nullable<MorphTargetManager> {
  2234. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  2235. if (this.morphTargetManagers[index].uniqueId === id) {
  2236. return this.morphTargetManagers[index];
  2237. }
  2238. }
  2239. return null;
  2240. }
  2241. public isActiveMesh(mesh: AbstractMesh): boolean {
  2242. return (this._activeMeshes.indexOf(mesh) !== -1);
  2243. }
  2244. /**
  2245. * Return a the first highlight layer of the scene with a given name.
  2246. * @param name The name of the highlight layer to look for.
  2247. * @return The highlight layer if found otherwise null.
  2248. */
  2249. public getHighlightLayerByName(name: string): Nullable<HighlightLayer> {
  2250. for (var index = 0; index < this.highlightLayers.length; index++) {
  2251. if (this.highlightLayers[index].name === name) {
  2252. return this.highlightLayers[index];
  2253. }
  2254. }
  2255. return null;
  2256. }
  2257. /**
  2258. * Return a unique id as a string which can serve as an identifier for the scene
  2259. */
  2260. public get uid(): string {
  2261. if (!this._uid) {
  2262. this._uid = Tools.RandomId();
  2263. }
  2264. return this._uid;
  2265. }
  2266. /**
  2267. * Add an externaly attached data from its key.
  2268. * This method call will fail and return false, if such key already exists.
  2269. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2270. * @param key the unique key that identifies the data
  2271. * @param data the data object to associate to the key for this Engine instance
  2272. * @return true if no such key were already present and the data was added successfully, false otherwise
  2273. */
  2274. public addExternalData<T>(key: string, data: T): boolean {
  2275. if (!this._externalData) {
  2276. this._externalData = new StringDictionary<Object>();
  2277. }
  2278. return this._externalData.add(key, data);
  2279. }
  2280. /**
  2281. * Get an externaly attached data from its key
  2282. * @param key the unique key that identifies the data
  2283. * @return the associated data, if present (can be null), or undefined if not present
  2284. */
  2285. public getExternalData<T>(key: string): Nullable<T> {
  2286. if (!this._externalData) {
  2287. return null;
  2288. }
  2289. return <T>this._externalData.get(key);
  2290. }
  2291. /**
  2292. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2293. * @param key the unique key that identifies the data
  2294. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2295. * @return the associated data, can be null if the factory returned null.
  2296. */
  2297. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  2298. if (!this._externalData) {
  2299. this._externalData = new StringDictionary<Object>();
  2300. }
  2301. return <T>this._externalData.getOrAddWithFactory(key, factory);
  2302. }
  2303. /**
  2304. * Remove an externaly attached data from the Engine instance
  2305. * @param key the unique key that identifies the data
  2306. * @return true if the data was successfully removed, false if it doesn't exist
  2307. */
  2308. public removeExternalData(key: string): boolean {
  2309. return this._externalData.remove(key);
  2310. }
  2311. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  2312. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  2313. var material = subMesh.getMaterial();
  2314. if (mesh.showSubMeshesBoundingBox) {
  2315. let boundingInfo = subMesh.getBoundingInfo();
  2316. if (boundingInfo) {
  2317. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  2318. }
  2319. }
  2320. if (material) {
  2321. // Render targets
  2322. if (material.getRenderTargetTextures) {
  2323. if (this._processedMaterials.indexOf(material) === -1) {
  2324. this._processedMaterials.push(material);
  2325. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  2326. }
  2327. }
  2328. // Dispatch
  2329. this._activeIndices.addCount(subMesh.indexCount, false);
  2330. this._renderingManager.dispatch(subMesh);
  2331. }
  2332. }
  2333. }
  2334. public _isInIntermediateRendering(): boolean {
  2335. return this._intermediateRendering
  2336. }
  2337. private _activeMeshesFrozen = false;
  2338. /**
  2339. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  2340. */
  2341. public freezeActiveMeshes(): Scene {
  2342. this._evaluateActiveMeshes();
  2343. this._activeMeshesFrozen = true;
  2344. return this;
  2345. }
  2346. /**
  2347. * Use this function to restart evaluating active meshes on every frame
  2348. */
  2349. public unfreezeActiveMeshes() {
  2350. this._activeMeshesFrozen = false;
  2351. return this;
  2352. }
  2353. private _evaluateActiveMeshes(): void {
  2354. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  2355. return;
  2356. }
  2357. if (!this.activeCamera) {
  2358. return;
  2359. }
  2360. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  2361. this.activeCamera._activeMeshes.reset();
  2362. this._activeMeshes.reset();
  2363. this._renderingManager.reset();
  2364. this._processedMaterials.reset();
  2365. this._activeParticleSystems.reset();
  2366. this._activeSkeletons.reset();
  2367. this._softwareSkinnedMeshes.reset();
  2368. if (this._boundingBoxRenderer) {
  2369. this._boundingBoxRenderer.reset();
  2370. }
  2371. // Meshes
  2372. var meshes: AbstractMesh[];
  2373. var len: number;
  2374. if (this._selectionOctree) { // Octree
  2375. var selection = this._selectionOctree.select(this._frustumPlanes);
  2376. meshes = selection.data;
  2377. len = selection.length;
  2378. } else { // Full scene traversal
  2379. len = this.meshes.length;
  2380. meshes = this.meshes;
  2381. }
  2382. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  2383. var mesh = meshes[meshIndex];
  2384. if (mesh.isBlocked) {
  2385. continue;
  2386. }
  2387. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  2388. if (!mesh.isReady() || !mesh.isEnabled()) {
  2389. continue;
  2390. }
  2391. mesh.computeWorldMatrix();
  2392. // Intersections
  2393. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  2394. this._meshesForIntersections.pushNoDuplicate(mesh);
  2395. }
  2396. // Switch to current LOD
  2397. var meshLOD = mesh.getLOD(this.activeCamera);
  2398. if (!meshLOD) {
  2399. continue;
  2400. }
  2401. mesh._preActivate();
  2402. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  2403. this._activeMeshes.push(mesh);
  2404. this.activeCamera._activeMeshes.push(mesh);
  2405. mesh._activate(this._renderId);
  2406. if (meshLOD !== mesh) {
  2407. meshLOD._activate(this._renderId);
  2408. }
  2409. this._activeMesh(mesh, meshLOD);
  2410. }
  2411. }
  2412. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  2413. // Particle systems
  2414. if (this.particlesEnabled) {
  2415. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  2416. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  2417. var particleSystem = this.particleSystems[particleIndex];
  2418. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  2419. continue;
  2420. }
  2421. let emitter = <any>particleSystem.emitter;
  2422. if (!emitter.position || emitter.isEnabled()) {
  2423. this._activeParticleSystems.push(particleSystem);
  2424. particleSystem.animate();
  2425. this._renderingManager.dispatchParticles(particleSystem);
  2426. }
  2427. }
  2428. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  2429. }
  2430. }
  2431. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  2432. if (mesh.skeleton && this.skeletonsEnabled) {
  2433. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  2434. mesh.skeleton.prepare();
  2435. }
  2436. if (!mesh.computeBonesUsingShaders) {
  2437. this._softwareSkinnedMeshes.pushNoDuplicate(<Mesh>mesh);
  2438. }
  2439. }
  2440. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  2441. let boundingInfo = sourceMesh.getBoundingInfo();
  2442. if (boundingInfo) {
  2443. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  2444. }
  2445. }
  2446. if (mesh && mesh.subMeshes) {
  2447. // Submeshes Octrees
  2448. var len: number;
  2449. var subMeshes: SubMesh[];
  2450. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  2451. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  2452. len = intersections.length;
  2453. subMeshes = intersections.data;
  2454. } else {
  2455. subMeshes = mesh.subMeshes;
  2456. len = subMeshes.length;
  2457. }
  2458. for (var subIndex = 0; subIndex < len; subIndex++) {
  2459. var subMesh = subMeshes[subIndex];
  2460. this._evaluateSubMesh(subMesh, mesh);
  2461. }
  2462. }
  2463. }
  2464. public updateTransformMatrix(force?: boolean): void {
  2465. if (!this.activeCamera) {
  2466. return;
  2467. }
  2468. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  2469. }
  2470. public updateAlternateTransformMatrix(alternateCamera: Camera): void {
  2471. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  2472. }
  2473. private _renderForCamera(camera: Camera): void {
  2474. if (camera && camera._skipRendering) {
  2475. return;
  2476. }
  2477. var engine = this._engine;
  2478. this.activeCamera = camera;
  2479. if (!this.activeCamera)
  2480. throw new Error("Active camera not set");
  2481. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2482. // Viewport
  2483. engine.setViewport(this.activeCamera.viewport);
  2484. // Camera
  2485. this.resetCachedMaterial();
  2486. this._renderId++;
  2487. this.activeCamera.update();
  2488. this.updateTransformMatrix();
  2489. if (camera._alternateCamera) {
  2490. this.updateAlternateTransformMatrix(camera._alternateCamera);
  2491. this._alternateRendering = true;
  2492. }
  2493. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  2494. // Meshes
  2495. this._evaluateActiveMeshes();
  2496. // Software skinning
  2497. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  2498. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  2499. mesh.applySkeleton(<Skeleton>mesh.skeleton);
  2500. }
  2501. // Render targets
  2502. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  2503. var needsRestoreFrameBuffer = false;
  2504. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  2505. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  2506. }
  2507. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  2508. this._intermediateRendering = true;
  2509. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2510. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  2511. let renderTarget = this._renderTargets.data[renderIndex];
  2512. if (renderTarget._shouldRender()) {
  2513. this._renderId++;
  2514. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  2515. renderTarget.render((<boolean>hasSpecialRenderTargetCamera), this.dumpNextRenderTargets);
  2516. }
  2517. }
  2518. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2519. this._intermediateRendering = false;
  2520. this._renderId++;
  2521. needsRestoreFrameBuffer = true; // Restore back buffer
  2522. }
  2523. // Render HighlightLayer Texture
  2524. var stencilState = this._engine.getStencilBuffer();
  2525. var renderhighlights = false;
  2526. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  2527. this._intermediateRendering = true;
  2528. for (let i = 0; i < this.highlightLayers.length; i++) {
  2529. let highlightLayer = this.highlightLayers[i];
  2530. if (highlightLayer.shouldRender() &&
  2531. (!highlightLayer.camera ||
  2532. (highlightLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  2533. (highlightLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  2534. renderhighlights = true;
  2535. let renderTarget = (<RenderTargetTexture>(<any>highlightLayer)._mainTexture);
  2536. if (renderTarget._shouldRender()) {
  2537. this._renderId++;
  2538. renderTarget.render(false, false);
  2539. needsRestoreFrameBuffer = true;
  2540. }
  2541. }
  2542. }
  2543. this._intermediateRendering = false;
  2544. this._renderId++;
  2545. }
  2546. if (needsRestoreFrameBuffer) {
  2547. engine.restoreDefaultFramebuffer(); // Restore back buffer
  2548. }
  2549. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  2550. // Prepare Frame
  2551. this.postProcessManager._prepareFrame();
  2552. // Backgrounds
  2553. var layerIndex;
  2554. var layer;
  2555. if (this.layers.length) {
  2556. engine.setDepthBuffer(false);
  2557. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2558. layer = this.layers[layerIndex];
  2559. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  2560. layer.render();
  2561. }
  2562. }
  2563. engine.setDepthBuffer(true);
  2564. }
  2565. // Activate HighlightLayer stencil
  2566. if (renderhighlights) {
  2567. this._engine.setStencilBuffer(true);
  2568. }
  2569. // Render
  2570. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  2571. this._renderingManager.render(null, null, true, true);
  2572. this.onAfterDrawPhaseObservable.notifyObservers(this);
  2573. // Restore HighlightLayer stencil
  2574. if (renderhighlights) {
  2575. this._engine.setStencilBuffer(stencilState);
  2576. }
  2577. // Bounding boxes
  2578. if (this._boundingBoxRenderer) {
  2579. this._boundingBoxRenderer.render();
  2580. }
  2581. // Lens flares
  2582. if (this.lensFlaresEnabled) {
  2583. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2584. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  2585. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  2586. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  2587. lensFlareSystem.render();
  2588. }
  2589. }
  2590. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2591. }
  2592. // Foregrounds
  2593. if (this.layers.length) {
  2594. engine.setDepthBuffer(false);
  2595. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2596. layer = this.layers[layerIndex];
  2597. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  2598. layer.render();
  2599. }
  2600. }
  2601. engine.setDepthBuffer(true);
  2602. }
  2603. // Highlight Layer
  2604. if (renderhighlights) {
  2605. engine.setDepthBuffer(false);
  2606. for (let i = 0; i < this.highlightLayers.length; i++) {
  2607. if (this.highlightLayers[i].shouldRender()) {
  2608. this.highlightLayers[i].render();
  2609. }
  2610. }
  2611. engine.setDepthBuffer(true);
  2612. }
  2613. // Finalize frame
  2614. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  2615. // Reset some special arrays
  2616. this._renderTargets.reset();
  2617. this._alternateRendering = false;
  2618. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  2619. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2620. }
  2621. private _processSubCameras(camera: Camera): void {
  2622. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  2623. this._renderForCamera(camera);
  2624. return;
  2625. }
  2626. // Update camera
  2627. if (this.activeCamera) {
  2628. this.activeCamera.update();
  2629. }
  2630. // rig cameras
  2631. for (var index = 0; index < camera._rigCameras.length; index++) {
  2632. this._renderForCamera(camera._rigCameras[index]);
  2633. }
  2634. this.activeCamera = camera;
  2635. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  2636. }
  2637. private _checkIntersections(): void {
  2638. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  2639. var sourceMesh = this._meshesForIntersections.data[index];
  2640. if (!sourceMesh.actionManager) {
  2641. continue;
  2642. }
  2643. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  2644. var action = sourceMesh.actionManager.actions[actionIndex];
  2645. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2646. var parameters = action.getTriggerParameter();
  2647. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  2648. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  2649. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  2650. if (areIntersecting && currentIntersectionInProgress === -1) {
  2651. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  2652. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  2653. sourceMesh._intersectionsInProgress.push(otherMesh);
  2654. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2655. sourceMesh._intersectionsInProgress.push(otherMesh);
  2656. }
  2657. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  2658. //They intersected, and now they don't.
  2659. //is this trigger an exit trigger? execute an event.
  2660. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2661. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  2662. }
  2663. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  2664. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2665. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  2666. }
  2667. }
  2668. }
  2669. }
  2670. }
  2671. }
  2672. public render(): void {
  2673. if (this.isDisposed) {
  2674. return;
  2675. }
  2676. this._activeParticles.fetchNewFrame();
  2677. this._totalVertices.fetchNewFrame();
  2678. this._activeIndices.fetchNewFrame();
  2679. this._activeBones.fetchNewFrame();
  2680. this._meshesForIntersections.reset();
  2681. this.resetCachedMaterial();
  2682. this.onBeforeAnimationsObservable.notifyObservers(this);
  2683. // Actions
  2684. if (this.actionManager) {
  2685. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger);
  2686. }
  2687. //Simplification Queue
  2688. if (this.simplificationQueue && !this.simplificationQueue.running) {
  2689. this.simplificationQueue.executeNext();
  2690. }
  2691. if(this._engine.isDeterministicLockStep()){
  2692. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  2693. var defaultTimeStep = (60.0 / 1000.0);
  2694. if (this._physicsEngine) {
  2695. defaultTimeStep = this._physicsEngine.getTimeStep();
  2696. }
  2697. var maxSubSteps = this._engine.getLockstepMaxSteps();
  2698. this._timeAccumulator += deltaTime;
  2699. // compute the amount of fixed steps we should have taken since the last step
  2700. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  2701. internalSteps = Math.min(internalSteps, maxSubSteps);
  2702. for(this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++){
  2703. this.onBeforeStepObservable.notifyObservers(this);
  2704. // Animations
  2705. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  2706. this._animate();
  2707. // Physics
  2708. if (this._physicsEngine) {
  2709. Tools.StartPerformanceCounter("Physics");
  2710. this._physicsEngine._step(defaultTimeStep);
  2711. Tools.EndPerformanceCounter("Physics");
  2712. }
  2713. this._timeAccumulator -= defaultTimeStep;
  2714. this.onAfterStepObservable.notifyObservers(this);
  2715. this._currentStepId++;
  2716. if((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  2717. this._evaluateActiveMeshes();
  2718. }
  2719. }
  2720. }
  2721. else {
  2722. // Animations
  2723. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  2724. this._animationRatio = deltaTime * (60.0 / 1000.0);
  2725. this._animate();
  2726. // Physics
  2727. if (this._physicsEngine) {
  2728. Tools.StartPerformanceCounter("Physics");
  2729. this._physicsEngine._step(deltaTime / 1000.0);
  2730. Tools.EndPerformanceCounter("Physics");
  2731. }
  2732. }
  2733. // Before render
  2734. this.onBeforeRenderObservable.notifyObservers(this);
  2735. // Customs render targets
  2736. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  2737. var engine = this.getEngine();
  2738. var currentActiveCamera = this.activeCamera;
  2739. if (this.renderTargetsEnabled) {
  2740. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  2741. this._intermediateRendering = true;
  2742. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  2743. var renderTarget = this.customRenderTargets[customIndex];
  2744. if (renderTarget._shouldRender()) {
  2745. this._renderId++;
  2746. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  2747. if (!this.activeCamera)
  2748. throw new Error("Active camera not set");
  2749. // Viewport
  2750. engine.setViewport(this.activeCamera.viewport);
  2751. // Camera
  2752. this.updateTransformMatrix();
  2753. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  2754. }
  2755. }
  2756. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  2757. this._intermediateRendering = false;
  2758. this._renderId++;
  2759. }
  2760. // Restore back buffer
  2761. if (this.customRenderTargets.length > 0) {
  2762. engine.restoreDefaultFramebuffer();
  2763. }
  2764. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  2765. this.activeCamera = currentActiveCamera;
  2766. // Procedural textures
  2767. if (this.proceduralTexturesEnabled) {
  2768. Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  2769. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  2770. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  2771. if (proceduralTexture._shouldRender()) {
  2772. proceduralTexture.render();
  2773. }
  2774. }
  2775. Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  2776. }
  2777. // Clear
  2778. if (this.autoClearDepthAndStencil || this.autoClear) {
  2779. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  2780. }
  2781. // Shadows
  2782. if (this.shadowsEnabled) {
  2783. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  2784. var light = this.lights[lightIndex];
  2785. var shadowGenerator = light.getShadowGenerator();
  2786. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  2787. var shadowMap = <RenderTargetTexture>(shadowGenerator.getShadowMap());
  2788. if (this.textures.indexOf(shadowMap) !== -1) {
  2789. this._renderTargets.push(shadowMap);
  2790. }
  2791. }
  2792. }
  2793. }
  2794. // Depth renderer
  2795. if (this._depthRenderer) {
  2796. this._renderTargets.push(this._depthRenderer.getDepthMap());
  2797. }
  2798. // Geometry renderer
  2799. if (this._geometryBufferRenderer) {
  2800. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  2801. }
  2802. // RenderPipeline
  2803. if (this._postProcessRenderPipelineManager) {
  2804. this._postProcessRenderPipelineManager.update();
  2805. }
  2806. // Multi-cameras?
  2807. if (this.activeCameras.length > 0) {
  2808. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  2809. if (cameraIndex > 0) {
  2810. this._engine.clear(null, false, true, true);
  2811. }
  2812. this._processSubCameras(this.activeCameras[cameraIndex]);
  2813. }
  2814. } else {
  2815. if (!this.activeCamera) {
  2816. throw new Error("No camera defined");
  2817. }
  2818. this._processSubCameras(this.activeCamera);
  2819. }
  2820. // Intersection checks
  2821. this._checkIntersections();
  2822. // Update the audio listener attached to the camera
  2823. if (AudioEngine) {
  2824. this._updateAudioParameters();
  2825. }
  2826. // After render
  2827. if (this.afterRender) {
  2828. this.afterRender();
  2829. }
  2830. this.onAfterRenderObservable.notifyObservers(this);
  2831. // Cleaning
  2832. for (var index = 0; index < this._toBeDisposed.length; index++) {
  2833. var data = this._toBeDisposed.data[index];
  2834. if (data) {
  2835. data.dispose();
  2836. }
  2837. this._toBeDisposed[index] = null;
  2838. }
  2839. this._toBeDisposed.reset();
  2840. if (this.dumpNextRenderTargets) {
  2841. this.dumpNextRenderTargets = false;
  2842. }
  2843. this._activeBones.addCount(0, true);
  2844. this._activeIndices.addCount(0, true);
  2845. this._activeParticles.addCount(0, true);
  2846. }
  2847. private _updateAudioParameters() {
  2848. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  2849. return;
  2850. }
  2851. var listeningCamera: Nullable<Camera>;
  2852. var audioEngine = Engine.audioEngine;
  2853. if (this.activeCameras.length > 0) {
  2854. listeningCamera = this.activeCameras[0];
  2855. } else {
  2856. listeningCamera = this.activeCamera;
  2857. }
  2858. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  2859. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  2860. // for VR cameras
  2861. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  2862. listeningCamera = listeningCamera.rigCameras[0];
  2863. }
  2864. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  2865. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  2866. cameraDirection.normalize();
  2867. // To avoid some errors on GearVR
  2868. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  2869. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  2870. }
  2871. var i: number;
  2872. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2873. var sound = this.mainSoundTrack.soundCollection[i];
  2874. if (sound.useCustomAttenuation) {
  2875. sound.updateDistanceFromListener();
  2876. }
  2877. }
  2878. for (i = 0; i < this.soundTracks.length; i++) {
  2879. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2880. sound = this.soundTracks[i].soundCollection[j];
  2881. if (sound.useCustomAttenuation) {
  2882. sound.updateDistanceFromListener();
  2883. }
  2884. }
  2885. }
  2886. }
  2887. }
  2888. // Audio
  2889. public get audioEnabled(): boolean {
  2890. return this._audioEnabled;
  2891. }
  2892. public set audioEnabled(value: boolean) {
  2893. this._audioEnabled = value;
  2894. if (AudioEngine) {
  2895. if (this._audioEnabled) {
  2896. this._enableAudio();
  2897. }
  2898. else {
  2899. this._disableAudio();
  2900. }
  2901. }
  2902. }
  2903. private _disableAudio() {
  2904. var i: number;
  2905. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2906. this.mainSoundTrack.soundCollection[i].pause();
  2907. }
  2908. for (i = 0; i < this.soundTracks.length; i++) {
  2909. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2910. this.soundTracks[i].soundCollection[j].pause();
  2911. }
  2912. }
  2913. }
  2914. private _enableAudio() {
  2915. var i: number;
  2916. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2917. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  2918. this.mainSoundTrack.soundCollection[i].play();
  2919. }
  2920. }
  2921. for (i = 0; i < this.soundTracks.length; i++) {
  2922. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2923. if (this.soundTracks[i].soundCollection[j].isPaused) {
  2924. this.soundTracks[i].soundCollection[j].play();
  2925. }
  2926. }
  2927. }
  2928. }
  2929. public get headphone(): boolean {
  2930. return this._headphone;
  2931. }
  2932. public set headphone(value: boolean) {
  2933. this._headphone = value;
  2934. if (AudioEngine) {
  2935. if (this._headphone) {
  2936. this._switchAudioModeForHeadphones();
  2937. }
  2938. else {
  2939. this._switchAudioModeForNormalSpeakers();
  2940. }
  2941. }
  2942. }
  2943. private _switchAudioModeForHeadphones() {
  2944. this.mainSoundTrack.switchPanningModelToHRTF();
  2945. for (var i = 0; i < this.soundTracks.length; i++) {
  2946. this.soundTracks[i].switchPanningModelToHRTF();
  2947. }
  2948. }
  2949. private _switchAudioModeForNormalSpeakers() {
  2950. this.mainSoundTrack.switchPanningModelToEqualPower();
  2951. for (var i = 0; i < this.soundTracks.length; i++) {
  2952. this.soundTracks[i].switchPanningModelToEqualPower();
  2953. }
  2954. }
  2955. public enableDepthRenderer(): DepthRenderer {
  2956. if (this._depthRenderer) {
  2957. return this._depthRenderer;
  2958. }
  2959. this._depthRenderer = new DepthRenderer(this);
  2960. return this._depthRenderer;
  2961. }
  2962. public disableDepthRenderer(): void {
  2963. if (!this._depthRenderer) {
  2964. return;
  2965. }
  2966. this._depthRenderer.dispose();
  2967. this._depthRenderer = null;
  2968. }
  2969. public enableGeometryBufferRenderer(ratio: number = 1): Nullable<GeometryBufferRenderer> {
  2970. if (this._geometryBufferRenderer) {
  2971. return this._geometryBufferRenderer;
  2972. }
  2973. this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio);
  2974. if (!this._geometryBufferRenderer.isSupported) {
  2975. this._geometryBufferRenderer = null;
  2976. }
  2977. return this._geometryBufferRenderer;
  2978. }
  2979. public disableGeometryBufferRenderer(): void {
  2980. if (!this._geometryBufferRenderer) {
  2981. return;
  2982. }
  2983. this._geometryBufferRenderer.dispose();
  2984. this._geometryBufferRenderer = null;
  2985. }
  2986. public freezeMaterials(): void {
  2987. for (var i = 0; i < this.materials.length; i++) {
  2988. this.materials[i].freeze();
  2989. }
  2990. }
  2991. public unfreezeMaterials(): void {
  2992. for (var i = 0; i < this.materials.length; i++) {
  2993. this.materials[i].unfreeze();
  2994. }
  2995. }
  2996. public dispose(): void {
  2997. this.beforeRender = null;
  2998. this.afterRender = null;
  2999. this.skeletons = [];
  3000. this.morphTargetManagers = [];
  3001. this.importedMeshesFiles = new Array<string>();
  3002. this.resetCachedMaterial();
  3003. if (this._depthRenderer) {
  3004. this._depthRenderer.dispose();
  3005. }
  3006. if (this._gamepadManager) {
  3007. this._gamepadManager.dispose();
  3008. this._gamepadManager = null;
  3009. }
  3010. // Smart arrays
  3011. if (this.activeCamera) {
  3012. this.activeCamera._activeMeshes.dispose();
  3013. this.activeCamera = null;
  3014. }
  3015. this._activeMeshes.dispose();
  3016. this._renderingManager.dispose();
  3017. this._processedMaterials.dispose();
  3018. this._activeParticleSystems.dispose();
  3019. this._activeSkeletons.dispose();
  3020. this._softwareSkinnedMeshes.dispose();
  3021. this._renderTargets.dispose();
  3022. if (this._boundingBoxRenderer) {
  3023. this._boundingBoxRenderer.dispose();
  3024. }
  3025. this._meshesForIntersections.dispose();
  3026. this._toBeDisposed.dispose();
  3027. // Debug layer
  3028. if (this._debugLayer) {
  3029. this._debugLayer.hide();
  3030. }
  3031. // Events
  3032. this.onDisposeObservable.notifyObservers(this);
  3033. this.onDisposeObservable.clear();
  3034. this.onBeforeRenderObservable.clear();
  3035. this.onAfterRenderObservable.clear();
  3036. this.OnBeforeRenderTargetsRenderObservable.clear();
  3037. this.OnAfterRenderTargetsRenderObservable.clear();
  3038. this.onAfterStepObservable.clear();
  3039. this.onBeforeStepObservable.clear();
  3040. this.onBeforeActiveMeshesEvaluationObservable.clear();
  3041. this.onAfterActiveMeshesEvaluationObservable.clear();
  3042. this.onBeforeParticlesRenderingObservable.clear();
  3043. this.onAfterParticlesRenderingObservable.clear();
  3044. this.onBeforeSpritesRenderingObservable.clear();
  3045. this.onAfterSpritesRenderingObservable.clear();
  3046. this.onBeforeDrawPhaseObservable.clear();
  3047. this.onAfterDrawPhaseObservable.clear();
  3048. this.detachControl();
  3049. // Release sounds & sounds tracks
  3050. if (AudioEngine) {
  3051. this.disposeSounds();
  3052. }
  3053. // VR Helper
  3054. if (this.VRHelper) {
  3055. this.VRHelper.dispose();
  3056. }
  3057. // Detach cameras
  3058. var canvas = this._engine.getRenderingCanvas();
  3059. if (canvas) {
  3060. var index;
  3061. for (index = 0; index < this.cameras.length; index++) {
  3062. this.cameras[index].detachControl(canvas);
  3063. }
  3064. }
  3065. // Release lights
  3066. while (this.lights.length) {
  3067. this.lights[0].dispose();
  3068. }
  3069. // Release meshes
  3070. while (this.meshes.length) {
  3071. this.meshes[0].dispose(true);
  3072. }
  3073. // Release cameras
  3074. while (this.cameras.length) {
  3075. this.cameras[0].dispose();
  3076. }
  3077. // Release materials
  3078. if (this.defaultMaterial) {
  3079. this.defaultMaterial.dispose()
  3080. }
  3081. while (this.multiMaterials.length) {
  3082. this.multiMaterials[0].dispose();
  3083. }
  3084. while (this.materials.length) {
  3085. this.materials[0].dispose();
  3086. }
  3087. // Release particles
  3088. while (this.particleSystems.length) {
  3089. this.particleSystems[0].dispose();
  3090. }
  3091. // Release sprites
  3092. while (this.spriteManagers.length) {
  3093. this.spriteManagers[0].dispose();
  3094. }
  3095. // Release postProcesses
  3096. while (this.postProcesses.length) {
  3097. this.postProcesses[0].dispose();
  3098. }
  3099. // Release layers
  3100. while (this.layers.length) {
  3101. this.layers[0].dispose();
  3102. }
  3103. while (this.highlightLayers.length) {
  3104. this.highlightLayers[0].dispose();
  3105. }
  3106. // Release textures
  3107. while (this.textures.length) {
  3108. this.textures[0].dispose();
  3109. }
  3110. // Release UBO
  3111. this._sceneUbo.dispose();
  3112. if (this._alternateSceneUbo) {
  3113. this._alternateSceneUbo.dispose();
  3114. }
  3115. // Post-processes
  3116. this.postProcessManager.dispose();
  3117. if (this._postProcessRenderPipelineManager) {
  3118. this._postProcessRenderPipelineManager.dispose();
  3119. }
  3120. // Physics
  3121. if (this._physicsEngine) {
  3122. this.disablePhysicsEngine();
  3123. }
  3124. // Remove from engine
  3125. index = this._engine.scenes.indexOf(this);
  3126. if (index > -1) {
  3127. this._engine.scenes.splice(index, 1);
  3128. }
  3129. this._engine.wipeCaches();
  3130. this._isDisposed = true;
  3131. }
  3132. public get isDisposed(): boolean {
  3133. return this._isDisposed;
  3134. }
  3135. // Release sounds & sounds tracks
  3136. public disposeSounds() {
  3137. if (!this._mainSoundTrack) {
  3138. return;
  3139. }
  3140. this.mainSoundTrack.dispose();
  3141. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  3142. this.soundTracks[scIndex].dispose();
  3143. }
  3144. }
  3145. // Octrees
  3146. public getWorldExtends(): { min: Vector3; max: Vector3 } {
  3147. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3148. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3149. for (var index = 0; index < this.meshes.length; index++) {
  3150. var mesh = this.meshes[index];
  3151. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  3152. continue;
  3153. }
  3154. mesh.computeWorldMatrix(true);
  3155. let boundingInfo = mesh.getBoundingInfo();
  3156. if (boundingInfo) {
  3157. var minBox = boundingInfo.boundingBox.minimumWorld;
  3158. var maxBox = boundingInfo.boundingBox.maximumWorld;
  3159. Tools.CheckExtends(minBox, min, max);
  3160. Tools.CheckExtends(maxBox, min, max);
  3161. }
  3162. }
  3163. return {
  3164. min: min,
  3165. max: max
  3166. };
  3167. }
  3168. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  3169. if (!this._selectionOctree) {
  3170. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  3171. }
  3172. var worldExtends = this.getWorldExtends();
  3173. // Update octree
  3174. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  3175. return this._selectionOctree;
  3176. }
  3177. // Picking
  3178. public createPickingRay(x: number, y: number, world: Matrix, camera: Nullable<Camera>, cameraViewSpace = false): Ray {
  3179. var engine = this._engine;
  3180. if (!camera) {
  3181. if (!this.activeCamera)
  3182. throw new Error("Active camera not set");
  3183. camera = this.activeCamera;
  3184. }
  3185. var cameraViewport = camera.viewport;
  3186. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  3187. // Moving coordinates to local viewport world
  3188. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  3189. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  3190. return Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  3191. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  3192. }
  3193. public createPickingRayInCameraSpace(x: number, y: number, camera?: Camera): Nullable<Ray> {
  3194. if (!BABYLON.PickingInfo) {
  3195. return null;
  3196. }
  3197. var engine = this._engine;
  3198. if (!camera) {
  3199. if (!this.activeCamera)
  3200. throw new Error("Active camera not set");
  3201. camera = this.activeCamera;
  3202. }
  3203. var cameraViewport = camera.viewport;
  3204. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  3205. var identity = Matrix.Identity();
  3206. // Moving coordinates to local viewport world
  3207. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  3208. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  3209. return Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  3210. }
  3211. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  3212. if (!BABYLON.PickingInfo) {
  3213. return null;
  3214. }
  3215. var pickingInfo = null;
  3216. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3217. var mesh = this.meshes[meshIndex];
  3218. if (predicate) {
  3219. if (!predicate(mesh)) {
  3220. continue;
  3221. }
  3222. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  3223. continue;
  3224. }
  3225. var world = mesh.getWorldMatrix();
  3226. var ray = rayFunction(world);
  3227. var result = mesh.intersects(ray, fastCheck);
  3228. if (!result || !result.hit)
  3229. continue;
  3230. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  3231. continue;
  3232. pickingInfo = result;
  3233. if (fastCheck) {
  3234. break;
  3235. }
  3236. }
  3237. return pickingInfo || new PickingInfo();
  3238. }
  3239. private _internalMultiPick(rayFunction: (world: Matrix) => Ray, predicate?: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  3240. if (!BABYLON.PickingInfo) {
  3241. return null;
  3242. }
  3243. var pickingInfos = new Array<PickingInfo>();
  3244. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3245. var mesh = this.meshes[meshIndex];
  3246. if (predicate) {
  3247. if (!predicate(mesh)) {
  3248. continue;
  3249. }
  3250. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  3251. continue;
  3252. }
  3253. var world = mesh.getWorldMatrix();
  3254. var ray = rayFunction(world);
  3255. var result = mesh.intersects(ray, false);
  3256. if (!result || !result.hit)
  3257. continue;
  3258. pickingInfos.push(result);
  3259. }
  3260. return pickingInfos;
  3261. }
  3262. private _internalPickSprites(ray: Ray, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  3263. if (!BABYLON.PickingInfo) {
  3264. return null;
  3265. }
  3266. var pickingInfo = null;
  3267. if (!camera) {
  3268. if (!this.activeCamera) {
  3269. return null;
  3270. }
  3271. camera = this.activeCamera;
  3272. }
  3273. if (this.spriteManagers.length > 0) {
  3274. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  3275. var spriteManager = this.spriteManagers[spriteIndex];
  3276. if (!spriteManager.isPickable) {
  3277. continue;
  3278. }
  3279. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  3280. if (!result || !result.hit)
  3281. continue;
  3282. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  3283. continue;
  3284. pickingInfo = result;
  3285. if (fastCheck) {
  3286. break;
  3287. }
  3288. }
  3289. }
  3290. return pickingInfo || new PickingInfo();
  3291. }
  3292. /** Launch a ray to try to pick a mesh in the scene
  3293. * @param x position on screen
  3294. * @param y position on screen
  3295. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  3296. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3297. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3298. */
  3299. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Nullable<Camera>): Nullable<PickingInfo> {
  3300. return this._internalPick(world => this.createPickingRay(x, y, world, camera || null), predicate, fastCheck);
  3301. }
  3302. /** Launch a ray to try to pick a sprite in the scene
  3303. * @param x position on screen
  3304. * @param y position on screen
  3305. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  3306. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3307. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3308. */
  3309. public pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): Nullable<PickingInfo> {
  3310. let ray = this.createPickingRayInCameraSpace(x, y, camera);
  3311. if (!ray) {
  3312. return null;
  3313. }
  3314. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  3315. }
  3316. /** Use the given ray to pick a mesh in the scene
  3317. * @param ray The ray to use to pick meshes
  3318. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  3319. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  3320. */
  3321. public pickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  3322. return this._internalPick(world => {
  3323. if (!this._pickWithRayInverseMatrix) {
  3324. this._pickWithRayInverseMatrix = Matrix.Identity();
  3325. }
  3326. world.invertToRef(this._pickWithRayInverseMatrix);
  3327. return Ray.Transform(ray, this._pickWithRayInverseMatrix);
  3328. }, predicate, fastCheck);
  3329. }
  3330. /**
  3331. * Launch a ray to try to pick a mesh in the scene
  3332. * @param x X position on screen
  3333. * @param y Y position on screen
  3334. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  3335. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3336. */
  3337. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera): Nullable<PickingInfo[]> {
  3338. return this._internalMultiPick(world => this.createPickingRay(x, y, world, camera || null), predicate);
  3339. }
  3340. /**
  3341. * Launch a ray to try to pick a mesh in the scene
  3342. * @param ray Ray to use
  3343. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  3344. */
  3345. public multiPickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo[]> {
  3346. return this._internalMultiPick(world => {
  3347. if (!this._pickWithRayInverseMatrix) {
  3348. this._pickWithRayInverseMatrix = Matrix.Identity();
  3349. }
  3350. world.invertToRef(this._pickWithRayInverseMatrix);
  3351. return Ray.Transform(ray, this._pickWithRayInverseMatrix);
  3352. }, predicate);
  3353. }
  3354. public setPointerOverMesh(mesh: Nullable<AbstractMesh>): void {
  3355. if (this._pointerOverMesh === mesh) {
  3356. return;
  3357. }
  3358. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  3359. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  3360. }
  3361. this._pointerOverMesh = mesh;
  3362. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  3363. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  3364. }
  3365. }
  3366. public getPointerOverMesh(): Nullable<AbstractMesh> {
  3367. return this._pointerOverMesh;
  3368. }
  3369. public setPointerOverSprite(sprite: Nullable<Sprite>): void {
  3370. if (this._pointerOverSprite === sprite) {
  3371. return;
  3372. }
  3373. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  3374. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  3375. }
  3376. this._pointerOverSprite = sprite;
  3377. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  3378. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  3379. }
  3380. }
  3381. public getPointerOverSprite(): Nullable<Sprite> {
  3382. return this._pointerOverSprite;
  3383. }
  3384. // Physics
  3385. public getPhysicsEngine(): Nullable<PhysicsEngine> {
  3386. return this._physicsEngine;
  3387. }
  3388. /**
  3389. * Enables physics to the current scene
  3390. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  3391. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  3392. * @return {boolean} was the physics engine initialized
  3393. */
  3394. public enablePhysics(gravity: Nullable<Vector3> = null, plugin?: IPhysicsEnginePlugin): boolean {
  3395. if (this._physicsEngine) {
  3396. return true;
  3397. }
  3398. try {
  3399. this._physicsEngine = new PhysicsEngine(gravity, plugin);
  3400. return true;
  3401. } catch (e) {
  3402. Tools.Error(e.message);
  3403. return false;
  3404. }
  3405. }
  3406. public disablePhysicsEngine(): void {
  3407. if (!this._physicsEngine) {
  3408. return;
  3409. }
  3410. this._physicsEngine.dispose();
  3411. this._physicsEngine = null;
  3412. }
  3413. public isPhysicsEnabled(): boolean {
  3414. return this._physicsEngine !== undefined;
  3415. }
  3416. public deleteCompoundImpostor(compound: any): void {
  3417. var mesh: AbstractMesh = compound.parts[0].mesh;
  3418. if (mesh.physicsImpostor) {
  3419. mesh.physicsImpostor.dispose(/*true*/);
  3420. mesh.physicsImpostor = null;
  3421. }
  3422. }
  3423. // Misc.
  3424. public _rebuildGeometries(): void {
  3425. for (var geometry of this._geometries) {
  3426. geometry._rebuild();
  3427. }
  3428. for (var mesh of this.meshes) {
  3429. mesh._rebuild();
  3430. }
  3431. if (this.postProcessManager) {
  3432. this.postProcessManager._rebuild();
  3433. }
  3434. for (var layer of this.layers) {
  3435. layer._rebuild();
  3436. }
  3437. for (var highlightLayer of this.highlightLayers) {
  3438. highlightLayer._rebuild();
  3439. }
  3440. if (this._boundingBoxRenderer) {
  3441. this._boundingBoxRenderer._rebuild();
  3442. }
  3443. for (var system of this.particleSystems) {
  3444. system.rebuild();
  3445. }
  3446. if (this._postProcessRenderPipelineManager) {
  3447. this._postProcessRenderPipelineManager._rebuild();
  3448. }
  3449. }
  3450. public _rebuildTextures(): void {
  3451. for (var texture of this.textures) {
  3452. texture._rebuild();
  3453. }
  3454. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  3455. }
  3456. public createDefaultCameraOrLight(createArcRotateCamera = false, replace = false, attachCameraControls = false) {
  3457. // Dispose existing camera or light in replace mode.
  3458. if (replace) {
  3459. if (this.activeCamera) {
  3460. this.activeCamera.dispose();
  3461. this.activeCamera = null;
  3462. }
  3463. if (this.lights) {
  3464. for (var i = 0; i < this.lights.length; i++) {
  3465. this.lights[i].dispose();
  3466. }
  3467. }
  3468. }
  3469. // Light
  3470. if (this.lights.length === 0) {
  3471. new HemisphericLight("default light", Vector3.Up(), this);
  3472. }
  3473. // Camera
  3474. if (!this.activeCamera) {
  3475. var worldExtends = this.getWorldExtends();
  3476. var worldSize = worldExtends.max.subtract(worldExtends.min);
  3477. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  3478. var camera: TargetCamera;
  3479. var radius = worldSize.length() * 1.5;
  3480. if (createArcRotateCamera) {
  3481. var arcRotateCamera = new ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  3482. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  3483. arcRotateCamera.wheelPrecision = 100 / radius;
  3484. camera = arcRotateCamera;
  3485. }
  3486. else {
  3487. var freeCamera = new FreeCamera("default camera", new Vector3(worldCenter.x, worldCenter.y, -radius), this);
  3488. freeCamera.setTarget(worldCenter);
  3489. camera = freeCamera;
  3490. }
  3491. camera.minZ = radius * 0.01;
  3492. camera.maxZ = radius * 100;
  3493. camera.speed = radius * 0.2;
  3494. this.activeCamera = camera;
  3495. let canvas = this.getEngine().getRenderingCanvas();
  3496. if (attachCameraControls && canvas) {
  3497. camera.attachControl(canvas);
  3498. }
  3499. }
  3500. }
  3501. public createDefaultSkybox(environmentTexture?: BaseTexture, pbr = false, scale = 1000, blur = 0): Nullable<Mesh> {
  3502. if (environmentTexture) {
  3503. this.environmentTexture = environmentTexture;
  3504. }
  3505. if (!this.environmentTexture) {
  3506. Tools.Warn("Can not create default skybox without environment texture.");
  3507. return null;
  3508. }
  3509. // Skybox
  3510. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  3511. if (pbr) {
  3512. let hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  3513. hdrSkyboxMaterial.backFaceCulling = false;
  3514. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  3515. if (hdrSkyboxMaterial.reflectionTexture) {
  3516. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  3517. }
  3518. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  3519. hdrSkyboxMaterial.disableLighting = true;
  3520. hdrSkyboxMaterial.twoSidedLighting = true;
  3521. hdrSkybox.infiniteDistance = true;
  3522. hdrSkybox.material = hdrSkyboxMaterial;
  3523. }
  3524. else {
  3525. let skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  3526. skyboxMaterial.backFaceCulling = false;
  3527. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  3528. if (skyboxMaterial.reflectionTexture) {
  3529. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  3530. }
  3531. skyboxMaterial.disableLighting = true;
  3532. hdrSkybox.infiniteDistance = true;
  3533. hdrSkybox.material = skyboxMaterial;
  3534. }
  3535. return hdrSkybox;
  3536. }
  3537. public createDefaultVRExperience(webVROptions: WebVROptions = {}) {
  3538. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  3539. }
  3540. // Tags
  3541. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  3542. if (tagsQuery === undefined) {
  3543. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  3544. return list;
  3545. }
  3546. var listByTags = [];
  3547. forEach = forEach || ((item: any) => { return; });
  3548. for (var i in list) {
  3549. var item = list[i];
  3550. if (Tags.MatchesQuery(item, tagsQuery)) {
  3551. listByTags.push(item);
  3552. forEach(item);
  3553. }
  3554. }
  3555. return listByTags;
  3556. }
  3557. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  3558. return this._getByTags(this.meshes, tagsQuery, forEach);
  3559. }
  3560. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  3561. return this._getByTags(this.cameras, tagsQuery, forEach);
  3562. }
  3563. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  3564. return this._getByTags(this.lights, tagsQuery, forEach);
  3565. }
  3566. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  3567. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  3568. }
  3569. /**
  3570. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  3571. * This allowed control for front to back rendering or reversly depending of the special needs.
  3572. *
  3573. * @param renderingGroupId The rendering group id corresponding to its index
  3574. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  3575. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  3576. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  3577. */
  3578. public setRenderingOrder(renderingGroupId: number,
  3579. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  3580. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  3581. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  3582. this._renderingManager.setRenderingOrder(renderingGroupId,
  3583. opaqueSortCompareFn,
  3584. alphaTestSortCompareFn,
  3585. transparentSortCompareFn);
  3586. }
  3587. /**
  3588. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  3589. *
  3590. * @param renderingGroupId The rendering group id corresponding to its index
  3591. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  3592. * @param depth Automatically clears depth between groups if true and autoClear is true.
  3593. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  3594. */
  3595. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  3596. depth = true,
  3597. stencil = true): void {
  3598. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  3599. }
  3600. /**
  3601. * Will flag all materials as dirty to trigger new shader compilation
  3602. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  3603. */
  3604. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  3605. for (var material of this.materials) {
  3606. if (predicate && !predicate(material)) {
  3607. continue;
  3608. }
  3609. material.markAsDirty(flag);
  3610. }
  3611. }
  3612. }
  3613. }