scene.ts 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802
  1. import { Nullable } from "./types";
  2. import { Tools } from "./Misc/tools";
  3. import { IAnimatable } from './Animations/animatable.interface';
  4. import { PrecisionDate } from "./Misc/precisionDate";
  5. import { Observable, Observer } from "./Misc/observable";
  6. import { SmartArrayNoDuplicate, SmartArray, ISmartArrayLike } from "./Misc/smartArray";
  7. import { StringDictionary } from "./Misc/stringDictionary";
  8. import { Tags } from "./Misc/tags";
  9. import { Vector2, Vector3, Matrix } from "./Maths/math.vector";
  10. import { Geometry } from "./Meshes/geometry";
  11. import { TransformNode } from "./Meshes/transformNode";
  12. import { SubMesh } from "./Meshes/subMesh";
  13. import { AbstractMesh } from "./Meshes/abstractMesh";
  14. import { Mesh } from "./Meshes/mesh";
  15. import { IParticleSystem } from "./Particles/IParticleSystem";
  16. import { Bone } from "./Bones/bone";
  17. import { Skeleton } from "./Bones/skeleton";
  18. import { MorphTargetManager } from "./Morph/morphTargetManager";
  19. import { Camera } from "./Cameras/camera";
  20. import { AbstractScene } from "./abstractScene";
  21. import { BaseTexture } from "./Materials/Textures/baseTexture";
  22. import { Texture } from "./Materials/Textures/texture";
  23. import { RenderTargetTexture } from "./Materials/Textures/renderTargetTexture";
  24. import { Material } from "./Materials/material";
  25. import { ImageProcessingConfiguration } from "./Materials/imageProcessingConfiguration";
  26. import { Effect } from "./Materials/effect";
  27. import { UniformBuffer } from "./Materials/uniformBuffer";
  28. import { MultiMaterial } from "./Materials/multiMaterial";
  29. import { Light } from "./Lights/light";
  30. import { PickingInfo } from "./Collisions/pickingInfo";
  31. import { ICollisionCoordinator } from "./Collisions/collisionCoordinator";
  32. import { PointerEventTypes, PointerInfoPre, PointerInfo } from "./Events/pointerEvents";
  33. import { KeyboardInfoPre, KeyboardInfo } from "./Events/keyboardEvents";
  34. import { ActionEvent } from "./Actions/actionEvent";
  35. import { PostProcessManager } from "./PostProcesses/postProcessManager";
  36. import { IOfflineProvider } from "./Offline/IOfflineProvider";
  37. import { RenderingGroupInfo, RenderingManager, IRenderingManagerAutoClearSetup } from "./Rendering/renderingManager";
  38. import { ISceneComponent, ISceneSerializableComponent, Stage, SimpleStageAction, RenderTargetsStageAction, RenderTargetStageAction, MeshStageAction, EvaluateSubMeshStageAction, PreActiveMeshStageAction, CameraStageAction, RenderingGroupStageAction, RenderingMeshStageAction, PointerMoveStageAction, PointerUpDownStageAction, CameraStageFrameBufferAction } from "./sceneComponent";
  39. import { Engine } from "./Engines/engine";
  40. import { Node } from "./node";
  41. import { MorphTarget } from "./Morph/morphTarget";
  42. import { Constants } from "./Engines/constants";
  43. import { DomManagement } from "./Misc/domManagement";
  44. import { Logger } from "./Misc/logger";
  45. import { EngineStore } from "./Engines/engineStore";
  46. import { AbstractActionManager } from './Actions/abstractActionManager';
  47. import { _DevTools } from './Misc/devTools';
  48. import { WebRequest } from './Misc/webRequest';
  49. import { InputManager } from './Inputs/scene.inputManager';
  50. import { PerfCounter } from './Misc/perfCounter';
  51. import { IFileRequest } from './Misc/fileRequest';
  52. import { Color4, Color3 } from './Maths/math.color';
  53. import { Plane } from './Maths/math.plane';
  54. import { Frustum } from './Maths/math.frustum';
  55. import { UniqueIdGenerator } from './Misc/uniqueIdGenerator';
  56. import { FileTools, LoadFileError, RequestFileError, ReadFileError } from './Misc/fileTools';
  57. import { IClipPlanesHolder } from './Misc/interfaces/iClipPlanesHolder';
  58. declare type Ray = import("./Culling/ray").Ray;
  59. declare type TrianglePickingPredicate = import("./Culling/ray").TrianglePickingPredicate;
  60. declare type Animation = import("./Animations/animation").Animation;
  61. declare type Animatable = import("./Animations/animatable").Animatable;
  62. declare type AnimationGroup = import("./Animations/animationGroup").AnimationGroup;
  63. declare type AnimationPropertiesOverride = import("./Animations/animationPropertiesOverride").AnimationPropertiesOverride;
  64. declare type Collider = import("./Collisions/collider").Collider;
  65. declare type PostProcess = import("./PostProcesses/postProcess").PostProcess;
  66. /**
  67. * Define an interface for all classes that will hold resources
  68. */
  69. export interface IDisposable {
  70. /**
  71. * Releases all held resources
  72. */
  73. dispose(): void;
  74. }
  75. /** Interface defining initialization parameters for Scene class */
  76. export interface SceneOptions {
  77. /**
  78. * Defines that scene should keep up-to-date a map of geometry to enable fast look-up by uniqueId
  79. * It will improve performance when the number of geometries becomes important.
  80. */
  81. useGeometryUniqueIdsMap?: boolean;
  82. /**
  83. * Defines that each material of the scene should keep up-to-date a map of referencing meshes for fast diposing
  84. * It will improve performance when the number of mesh becomes important, but might consume a bit more memory
  85. */
  86. useMaterialMeshMap?: boolean;
  87. /**
  88. * Defines that each mesh of the scene should keep up-to-date a map of referencing cloned meshes for fast diposing
  89. * It will improve performance when the number of mesh becomes important, but might consume a bit more memory
  90. */
  91. useClonedMeshMap?: boolean;
  92. /** Defines if the creation of the scene should impact the engine (Eg. UtilityLayer's scene) */
  93. virtual?: boolean;
  94. }
  95. /**
  96. * Represents a scene to be rendered by the engine.
  97. * @see https://doc.babylonjs.com/features/scene
  98. */
  99. export class Scene extends AbstractScene implements IAnimatable, IClipPlanesHolder {
  100. /** The fog is deactivated */
  101. public static readonly FOGMODE_NONE = 0;
  102. /** The fog density is following an exponential function */
  103. public static readonly FOGMODE_EXP = 1;
  104. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  105. public static readonly FOGMODE_EXP2 = 2;
  106. /** The fog density is following a linear function. */
  107. public static readonly FOGMODE_LINEAR = 3;
  108. /**
  109. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  110. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  111. */
  112. public static MinDeltaTime = 1.0;
  113. /**
  114. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  115. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  116. */
  117. public static MaxDeltaTime = 1000.0;
  118. /**
  119. * Factory used to create the default material.
  120. * @param name The name of the material to create
  121. * @param scene The scene to create the material for
  122. * @returns The default material
  123. */
  124. public static DefaultMaterialFactory(scene: Scene): Material {
  125. throw _DevTools.WarnImport("StandardMaterial");
  126. }
  127. /**
  128. * Factory used to create the a collision coordinator.
  129. * @returns The collision coordinator
  130. */
  131. public static CollisionCoordinatorFactory(): ICollisionCoordinator {
  132. throw _DevTools.WarnImport("DefaultCollisionCoordinator");
  133. }
  134. // Members
  135. /** @hidden */
  136. public _inputManager = new InputManager(this);
  137. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  138. public cameraToUseForPointers: Nullable<Camera> = null;
  139. /** @hidden */
  140. public readonly _isScene = true;
  141. /** @hidden */
  142. public _blockEntityCollection = false;
  143. /**
  144. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  145. */
  146. public autoClear = true;
  147. /**
  148. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  149. */
  150. public autoClearDepthAndStencil = true;
  151. /**
  152. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  153. */
  154. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  155. /**
  156. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  157. */
  158. public ambientColor = new Color3(0, 0, 0);
  159. /**
  160. * This is use to store the default BRDF lookup for PBR materials in your scene.
  161. * It should only be one of the following (if not the default embedded one):
  162. * * For uncorrelated BRDF (pbr.brdf.useEnergyConservation = false and pbr.brdf.useSmithVisibilityHeightCorrelated = false) : https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds
  163. * * For correlated BRDF (pbr.brdf.useEnergyConservation = false and pbr.brdf.useSmithVisibilityHeightCorrelated = true) : https://assets.babylonjs.com/environments/correlatedBRDF.dds
  164. * * For correlated multi scattering BRDF (pbr.brdf.useEnergyConservation = true and pbr.brdf.useSmithVisibilityHeightCorrelated = true) : https://assets.babylonjs.com/environments/correlatedMSBRDF.dds
  165. * The material properties need to be setup according to the type of texture in use.
  166. */
  167. public environmentBRDFTexture: BaseTexture;
  168. /**
  169. * Texture used in all pbr material as the reflection texture.
  170. * As in the majority of the scene they are the same (exception for multi room and so on),
  171. * this is easier to reference from here than from all the materials.
  172. */
  173. public get environmentTexture(): Nullable<BaseTexture> {
  174. return this._environmentTexture;
  175. }
  176. /**
  177. * Texture used in all pbr material as the reflection texture.
  178. * As in the majority of the scene they are the same (exception for multi room and so on),
  179. * this is easier to set here than in all the materials.
  180. */
  181. public set environmentTexture(value: Nullable<BaseTexture>) {
  182. if (this._environmentTexture === value) {
  183. return;
  184. }
  185. this._environmentTexture = value;
  186. this.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  187. }
  188. /** @hidden */
  189. protected _environmentIntensity: number = 1;
  190. /**
  191. * Intensity of the environment in all pbr material.
  192. * This dims or reinforces the IBL lighting overall (reflection and diffuse).
  193. * As in the majority of the scene they are the same (exception for multi room and so on),
  194. * this is easier to reference from here than from all the materials.
  195. */
  196. public get environmentIntensity(): number {
  197. return this._environmentIntensity;
  198. }
  199. /**
  200. * Intensity of the environment in all pbr material.
  201. * This dims or reinforces the IBL lighting overall (reflection and diffuse).
  202. * As in the majority of the scene they are the same (exception for multi room and so on),
  203. * this is easier to set here than in all the materials.
  204. */
  205. public set environmentIntensity(value: number) {
  206. if (this._environmentIntensity === value) {
  207. return;
  208. }
  209. this._environmentIntensity = value;
  210. this.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  211. }
  212. /** @hidden */
  213. protected _imageProcessingConfiguration: ImageProcessingConfiguration;
  214. /**
  215. * Default image processing configuration used either in the rendering
  216. * Forward main pass or through the imageProcessingPostProcess if present.
  217. * As in the majority of the scene they are the same (exception for multi camera),
  218. * this is easier to reference from here than from all the materials and post process.
  219. *
  220. * No setter as we it is a shared configuration, you can set the values instead.
  221. */
  222. public get imageProcessingConfiguration(): ImageProcessingConfiguration {
  223. return this._imageProcessingConfiguration;
  224. }
  225. private _forceWireframe = false;
  226. /**
  227. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  228. */
  229. public set forceWireframe(value: boolean) {
  230. if (this._forceWireframe === value) {
  231. return;
  232. }
  233. this._forceWireframe = value;
  234. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  235. }
  236. public get forceWireframe(): boolean {
  237. return this._forceWireframe;
  238. }
  239. private _skipFrustumClipping = false;
  240. /**
  241. * Gets or sets a boolean indicating if we should skip the frustum clipping part of the active meshes selection
  242. */
  243. public set skipFrustumClipping(value: boolean) {
  244. if (this._skipFrustumClipping === value) {
  245. return;
  246. }
  247. this._skipFrustumClipping = value;
  248. }
  249. public get skipFrustumClipping(): boolean {
  250. return this._skipFrustumClipping;
  251. }
  252. private _forcePointsCloud = false;
  253. /**
  254. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  255. */
  256. public set forcePointsCloud(value: boolean) {
  257. if (this._forcePointsCloud === value) {
  258. return;
  259. }
  260. this._forcePointsCloud = value;
  261. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  262. }
  263. public get forcePointsCloud(): boolean {
  264. return this._forcePointsCloud;
  265. }
  266. /**
  267. * Gets or sets the active clipplane 1
  268. */
  269. public clipPlane: Nullable<Plane>;
  270. /**
  271. * Gets or sets the active clipplane 2
  272. */
  273. public clipPlane2: Nullable<Plane>;
  274. /**
  275. * Gets or sets the active clipplane 3
  276. */
  277. public clipPlane3: Nullable<Plane>;
  278. /**
  279. * Gets or sets the active clipplane 4
  280. */
  281. public clipPlane4: Nullable<Plane>;
  282. /**
  283. * Gets or sets the active clipplane 5
  284. */
  285. public clipPlane5: Nullable<Plane>;
  286. /**
  287. * Gets or sets the active clipplane 6
  288. */
  289. public clipPlane6: Nullable<Plane>;
  290. /**
  291. * Gets or sets a boolean indicating if animations are enabled
  292. */
  293. public animationsEnabled = true;
  294. private _animationPropertiesOverride: Nullable<AnimationPropertiesOverride> = null;
  295. /**
  296. * Gets or sets the animation properties override
  297. */
  298. public get animationPropertiesOverride(): Nullable<AnimationPropertiesOverride> {
  299. return this._animationPropertiesOverride;
  300. }
  301. public set animationPropertiesOverride(value: Nullable<AnimationPropertiesOverride>) {
  302. this._animationPropertiesOverride = value;
  303. }
  304. /**
  305. * Gets or sets a boolean indicating if a constant deltatime has to be used
  306. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  307. */
  308. public useConstantAnimationDeltaTime = false;
  309. /**
  310. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  311. * Please note that it requires to run a ray cast through the scene on every frame
  312. */
  313. public constantlyUpdateMeshUnderPointer = false;
  314. /**
  315. * Defines the HTML cursor to use when hovering over interactive elements
  316. */
  317. public hoverCursor = "pointer";
  318. /**
  319. * Defines the HTML default cursor to use (empty by default)
  320. */
  321. public defaultCursor: string = "";
  322. /**
  323. * Defines whether cursors are handled by the scene.
  324. */
  325. public doNotHandleCursors = false;
  326. /**
  327. * This is used to call preventDefault() on pointer down
  328. * in order to block unwanted artifacts like system double clicks
  329. */
  330. public preventDefaultOnPointerDown = true;
  331. /**
  332. * This is used to call preventDefault() on pointer up
  333. * in order to block unwanted artifacts like system double clicks
  334. */
  335. public preventDefaultOnPointerUp = true;
  336. // Metadata
  337. /**
  338. * Gets or sets user defined metadata
  339. */
  340. public metadata: any = null;
  341. /**
  342. * For internal use only. Please do not use.
  343. */
  344. public reservedDataStore: any = null;
  345. /**
  346. * Gets the name of the plugin used to load this scene (null by default)
  347. */
  348. public loadingPluginName: string;
  349. /**
  350. * Use this array to add regular expressions used to disable offline support for specific urls
  351. */
  352. public disableOfflineSupportExceptionRules = new Array<RegExp>();
  353. /**
  354. * An event triggered when the scene is disposed.
  355. */
  356. public onDisposeObservable = new Observable<Scene>();
  357. private _onDisposeObserver: Nullable<Observer<Scene>> = null;
  358. /** Sets a function to be executed when this scene is disposed. */
  359. public set onDispose(callback: () => void) {
  360. if (this._onDisposeObserver) {
  361. this.onDisposeObservable.remove(this._onDisposeObserver);
  362. }
  363. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  364. }
  365. /**
  366. * An event triggered before rendering the scene (right after animations and physics)
  367. */
  368. public onBeforeRenderObservable = new Observable<Scene>();
  369. private _onBeforeRenderObserver: Nullable<Observer<Scene>> = null;
  370. /** Sets a function to be executed before rendering this scene */
  371. public set beforeRender(callback: Nullable<() => void>) {
  372. if (this._onBeforeRenderObserver) {
  373. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  374. }
  375. if (callback) {
  376. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  377. }
  378. }
  379. /**
  380. * An event triggered after rendering the scene
  381. */
  382. public onAfterRenderObservable = new Observable<Scene>();
  383. /**
  384. * An event triggered after rendering the scene for an active camera (When scene.render is called this will be called after each camera)
  385. */
  386. public onAfterRenderCameraObservable = new Observable<Camera>();
  387. private _onAfterRenderObserver: Nullable<Observer<Scene>> = null;
  388. /** Sets a function to be executed after rendering this scene */
  389. public set afterRender(callback: Nullable<() => void>) {
  390. if (this._onAfterRenderObserver) {
  391. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  392. }
  393. if (callback) {
  394. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  395. }
  396. }
  397. /**
  398. * An event triggered before animating the scene
  399. */
  400. public onBeforeAnimationsObservable = new Observable<Scene>();
  401. /**
  402. * An event triggered after animations processing
  403. */
  404. public onAfterAnimationsObservable = new Observable<Scene>();
  405. /**
  406. * An event triggered before draw calls are ready to be sent
  407. */
  408. public onBeforeDrawPhaseObservable = new Observable<Scene>();
  409. /**
  410. * An event triggered after draw calls have been sent
  411. */
  412. public onAfterDrawPhaseObservable = new Observable<Scene>();
  413. /**
  414. * An event triggered when the scene is ready
  415. */
  416. public onReadyObservable = new Observable<Scene>();
  417. /**
  418. * An event triggered before rendering a camera
  419. */
  420. public onBeforeCameraRenderObservable = new Observable<Camera>();
  421. private _onBeforeCameraRenderObserver: Nullable<Observer<Camera>> = null;
  422. /** Sets a function to be executed before rendering a camera*/
  423. public set beforeCameraRender(callback: () => void) {
  424. if (this._onBeforeCameraRenderObserver) {
  425. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  426. }
  427. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  428. }
  429. /**
  430. * An event triggered after rendering a camera
  431. */
  432. public onAfterCameraRenderObservable = new Observable<Camera>();
  433. private _onAfterCameraRenderObserver: Nullable<Observer<Camera>> = null;
  434. /** Sets a function to be executed after rendering a camera*/
  435. public set afterCameraRender(callback: () => void) {
  436. if (this._onAfterCameraRenderObserver) {
  437. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  438. }
  439. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  440. }
  441. /**
  442. * An event triggered when active meshes evaluation is about to start
  443. */
  444. public onBeforeActiveMeshesEvaluationObservable = new Observable<Scene>();
  445. /**
  446. * An event triggered when active meshes evaluation is done
  447. */
  448. public onAfterActiveMeshesEvaluationObservable = new Observable<Scene>();
  449. /**
  450. * An event triggered when particles rendering is about to start
  451. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  452. */
  453. public onBeforeParticlesRenderingObservable = new Observable<Scene>();
  454. /**
  455. * An event triggered when particles rendering is done
  456. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  457. */
  458. public onAfterParticlesRenderingObservable = new Observable<Scene>();
  459. /**
  460. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  461. */
  462. public onDataLoadedObservable = new Observable<Scene>();
  463. /**
  464. * An event triggered when a camera is created
  465. */
  466. public onNewCameraAddedObservable = new Observable<Camera>();
  467. /**
  468. * An event triggered when a camera is removed
  469. */
  470. public onCameraRemovedObservable = new Observable<Camera>();
  471. /**
  472. * An event triggered when a light is created
  473. */
  474. public onNewLightAddedObservable = new Observable<Light>();
  475. /**
  476. * An event triggered when a light is removed
  477. */
  478. public onLightRemovedObservable = new Observable<Light>();
  479. /**
  480. * An event triggered when a geometry is created
  481. */
  482. public onNewGeometryAddedObservable = new Observable<Geometry>();
  483. /**
  484. * An event triggered when a geometry is removed
  485. */
  486. public onGeometryRemovedObservable = new Observable<Geometry>();
  487. /**
  488. * An event triggered when a transform node is created
  489. */
  490. public onNewTransformNodeAddedObservable = new Observable<TransformNode>();
  491. /**
  492. * An event triggered when a transform node is removed
  493. */
  494. public onTransformNodeRemovedObservable = new Observable<TransformNode>();
  495. /**
  496. * An event triggered when a mesh is created
  497. */
  498. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  499. /**
  500. * An event triggered when a mesh is removed
  501. */
  502. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  503. /**
  504. * An event triggered when a skeleton is created
  505. */
  506. public onNewSkeletonAddedObservable = new Observable<Skeleton>();
  507. /**
  508. * An event triggered when a skeleton is removed
  509. */
  510. public onSkeletonRemovedObservable = new Observable<Skeleton>();
  511. /**
  512. * An event triggered when a material is created
  513. */
  514. public onNewMaterialAddedObservable = new Observable<Material>();
  515. /**
  516. * An event triggered when a material is removed
  517. */
  518. public onMaterialRemovedObservable = new Observable<Material>();
  519. /**
  520. * An event triggered when a texture is created
  521. */
  522. public onNewTextureAddedObservable = new Observable<BaseTexture>();
  523. /**
  524. * An event triggered when a texture is removed
  525. */
  526. public onTextureRemovedObservable = new Observable<BaseTexture>();
  527. /**
  528. * An event triggered when render targets are about to be rendered
  529. * Can happen multiple times per frame.
  530. */
  531. public onBeforeRenderTargetsRenderObservable = new Observable<Scene>();
  532. /**
  533. * An event triggered when render targets were rendered.
  534. * Can happen multiple times per frame.
  535. */
  536. public onAfterRenderTargetsRenderObservable = new Observable<Scene>();
  537. /**
  538. * An event triggered before calculating deterministic simulation step
  539. */
  540. public onBeforeStepObservable = new Observable<Scene>();
  541. /**
  542. * An event triggered after calculating deterministic simulation step
  543. */
  544. public onAfterStepObservable = new Observable<Scene>();
  545. /**
  546. * An event triggered when the activeCamera property is updated
  547. */
  548. public onActiveCameraChanged = new Observable<Scene>();
  549. /**
  550. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  551. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  552. * 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)
  553. */
  554. public onBeforeRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  555. /**
  556. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  557. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  558. * 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)
  559. */
  560. public onAfterRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  561. /**
  562. * This Observable will when a mesh has been imported into the scene.
  563. */
  564. public onMeshImportedObservable = new Observable<AbstractMesh>();
  565. /**
  566. * This Observable will when an animation file has been imported into the scene.
  567. */
  568. public onAnimationFileImportedObservable = new Observable<Scene>();
  569. /**
  570. * Gets or sets a user defined funtion to select LOD from a mesh and a camera.
  571. * By default this function is undefined and Babylon.js will select LOD based on distance to camera
  572. */
  573. public customLODSelector: (mesh: AbstractMesh, camera: Camera) => Nullable<AbstractMesh>;
  574. // Animations
  575. /** @hidden */
  576. public _registeredForLateAnimationBindings = new SmartArrayNoDuplicate<any>(256);
  577. // Pointers
  578. /**
  579. * Gets or sets a predicate used to select candidate meshes for a pointer down event
  580. */
  581. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  582. /**
  583. * Gets or sets a predicate used to select candidate meshes for a pointer up event
  584. */
  585. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  586. /**
  587. * Gets or sets a predicate used to select candidate meshes for a pointer move event
  588. */
  589. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  590. /** Callback called when a pointer move is detected */
  591. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  592. /** Callback called when a pointer down is detected */
  593. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo, type: PointerEventTypes) => void;
  594. /** Callback called when a pointer up is detected */
  595. public onPointerUp: (evt: PointerEvent, pickInfo: Nullable<PickingInfo>, type: PointerEventTypes) => void;
  596. /** Callback called when a pointer pick is detected */
  597. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  598. /**
  599. * 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).
  600. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  601. */
  602. public onPrePointerObservable = new Observable<PointerInfoPre>();
  603. /**
  604. * Observable event triggered each time an input event is received from the rendering canvas
  605. */
  606. public onPointerObservable = new Observable<PointerInfo>();
  607. /**
  608. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  609. */
  610. public get unTranslatedPointer(): Vector2 {
  611. return this._inputManager.unTranslatedPointer;
  612. }
  613. /**
  614. * Gets or sets the distance in pixel that you have to move to prevent some events. Default is 10 pixels
  615. */
  616. public static get DragMovementThreshold() {
  617. return InputManager.DragMovementThreshold;
  618. }
  619. public static set DragMovementThreshold(value: number) {
  620. InputManager.DragMovementThreshold = value;
  621. }
  622. /**
  623. * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 500 ms
  624. */
  625. public static get LongPressDelay() {
  626. return InputManager.LongPressDelay;
  627. }
  628. public static set LongPressDelay(value: number) {
  629. InputManager.LongPressDelay = value;
  630. }
  631. /**
  632. * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 300 ms
  633. */
  634. public static get DoubleClickDelay() {
  635. return InputManager.DoubleClickDelay;
  636. }
  637. public static set DoubleClickDelay(value: number) {
  638. InputManager.DoubleClickDelay = value;
  639. }
  640. /** If you need to check double click without raising a single click at first click, enable this flag */
  641. public static get ExclusiveDoubleClickMode() {
  642. return InputManager.ExclusiveDoubleClickMode;
  643. }
  644. public static set ExclusiveDoubleClickMode(value: boolean) {
  645. InputManager.ExclusiveDoubleClickMode = value;
  646. }
  647. // Mirror
  648. /** @hidden */
  649. public _mirroredCameraPosition: Nullable<Vector3>;
  650. // Keyboard
  651. /**
  652. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  653. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  654. */
  655. public onPreKeyboardObservable = new Observable<KeyboardInfoPre>();
  656. /**
  657. * Observable event triggered each time an keyboard event is received from the hosting window
  658. */
  659. public onKeyboardObservable = new Observable<KeyboardInfo>();
  660. // Coordinates system
  661. private _useRightHandedSystem = false;
  662. /**
  663. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  664. */
  665. public set useRightHandedSystem(value: boolean) {
  666. if (this._useRightHandedSystem === value) {
  667. return;
  668. }
  669. this._useRightHandedSystem = value;
  670. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  671. }
  672. public get useRightHandedSystem(): boolean {
  673. return this._useRightHandedSystem;
  674. }
  675. // Deterministic lockstep
  676. private _timeAccumulator: number = 0;
  677. private _currentStepId: number = 0;
  678. private _currentInternalStep: number = 0;
  679. /**
  680. * Sets the step Id used by deterministic lock step
  681. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  682. * @param newStepId defines the step Id
  683. */
  684. public setStepId(newStepId: number): void {
  685. this._currentStepId = newStepId;
  686. }
  687. /**
  688. * Gets the step Id used by deterministic lock step
  689. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  690. * @returns the step Id
  691. */
  692. public getStepId(): number {
  693. return this._currentStepId;
  694. }
  695. /**
  696. * Gets the internal step used by deterministic lock step
  697. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  698. * @returns the internal step
  699. */
  700. public getInternalStep(): number {
  701. return this._currentInternalStep;
  702. }
  703. // Fog
  704. private _fogEnabled = true;
  705. /**
  706. * Gets or sets a boolean indicating if fog is enabled on this scene
  707. * @see https://doc.babylonjs.com/babylon101/environment#fog
  708. * (Default is true)
  709. */
  710. public set fogEnabled(value: boolean) {
  711. if (this._fogEnabled === value) {
  712. return;
  713. }
  714. this._fogEnabled = value;
  715. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  716. }
  717. public get fogEnabled(): boolean {
  718. return this._fogEnabled;
  719. }
  720. private _fogMode = Scene.FOGMODE_NONE;
  721. /**
  722. * Gets or sets the fog mode to use
  723. * @see https://doc.babylonjs.com/babylon101/environment#fog
  724. * | mode | value |
  725. * | --- | --- |
  726. * | FOGMODE_NONE | 0 |
  727. * | FOGMODE_EXP | 1 |
  728. * | FOGMODE_EXP2 | 2 |
  729. * | FOGMODE_LINEAR | 3 |
  730. */
  731. public set fogMode(value: number) {
  732. if (this._fogMode === value) {
  733. return;
  734. }
  735. this._fogMode = value;
  736. this.markAllMaterialsAsDirty(Constants.MATERIAL_MiscDirtyFlag);
  737. }
  738. public get fogMode(): number {
  739. return this._fogMode;
  740. }
  741. /**
  742. * Gets or sets the fog color to use
  743. * @see https://doc.babylonjs.com/babylon101/environment#fog
  744. * (Default is Color3(0.2, 0.2, 0.3))
  745. */
  746. public fogColor = new Color3(0.2, 0.2, 0.3);
  747. /**
  748. * Gets or sets the fog density to use
  749. * @see https://doc.babylonjs.com/babylon101/environment#fog
  750. * (Default is 0.1)
  751. */
  752. public fogDensity = 0.1;
  753. /**
  754. * Gets or sets the fog start distance to use
  755. * @see https://doc.babylonjs.com/babylon101/environment#fog
  756. * (Default is 0)
  757. */
  758. public fogStart = 0;
  759. /**
  760. * Gets or sets the fog end distance to use
  761. * @see https://doc.babylonjs.com/babylon101/environment#fog
  762. * (Default is 1000)
  763. */
  764. public fogEnd = 1000.0;
  765. /**
  766. * Flag indicating that the frame buffer binding is handled by another component
  767. */
  768. public prePass: boolean = false;
  769. // Lights
  770. private _shadowsEnabled = true;
  771. /**
  772. * Gets or sets a boolean indicating if shadows are enabled on this scene
  773. */
  774. public set shadowsEnabled(value: boolean) {
  775. if (this._shadowsEnabled === value) {
  776. return;
  777. }
  778. this._shadowsEnabled = value;
  779. this.markAllMaterialsAsDirty(Constants.MATERIAL_LightDirtyFlag);
  780. }
  781. public get shadowsEnabled(): boolean {
  782. return this._shadowsEnabled;
  783. }
  784. private _lightsEnabled = true;
  785. /**
  786. * Gets or sets a boolean indicating if lights are enabled on this scene
  787. */
  788. public set lightsEnabled(value: boolean) {
  789. if (this._lightsEnabled === value) {
  790. return;
  791. }
  792. this._lightsEnabled = value;
  793. this.markAllMaterialsAsDirty(Constants.MATERIAL_LightDirtyFlag);
  794. }
  795. public get lightsEnabled(): boolean {
  796. return this._lightsEnabled;
  797. }
  798. /** All of the active cameras added to this scene. */
  799. public activeCameras = new Array<Camera>();
  800. /** @hidden */
  801. public _activeCamera: Nullable<Camera>;
  802. /** Gets or sets the current active camera */
  803. public get activeCamera(): Nullable<Camera> {
  804. return this._activeCamera;
  805. }
  806. public set activeCamera(value: Nullable<Camera>) {
  807. if (value === this._activeCamera) {
  808. return;
  809. }
  810. this._activeCamera = value;
  811. this.onActiveCameraChanged.notifyObservers(this);
  812. }
  813. private _defaultMaterial: Material;
  814. /** The default material used on meshes when no material is affected */
  815. public get defaultMaterial(): Material {
  816. if (!this._defaultMaterial) {
  817. this._defaultMaterial = Scene.DefaultMaterialFactory(this);
  818. }
  819. return this._defaultMaterial;
  820. }
  821. /** The default material used on meshes when no material is affected */
  822. public set defaultMaterial(value: Material) {
  823. this._defaultMaterial = value;
  824. }
  825. // Textures
  826. private _texturesEnabled = true;
  827. /**
  828. * Gets or sets a boolean indicating if textures are enabled on this scene
  829. */
  830. public set texturesEnabled(value: boolean) {
  831. if (this._texturesEnabled === value) {
  832. return;
  833. }
  834. this._texturesEnabled = value;
  835. this.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  836. }
  837. public get texturesEnabled(): boolean {
  838. return this._texturesEnabled;
  839. }
  840. // Physics
  841. /**
  842. * Gets or sets a boolean indicating if physic engines are enabled on this scene
  843. */
  844. public physicsEnabled = true;
  845. // Particles
  846. /**
  847. * Gets or sets a boolean indicating if particles are enabled on this scene
  848. */
  849. public particlesEnabled = true;
  850. // Sprites
  851. /**
  852. * Gets or sets a boolean indicating if sprites are enabled on this scene
  853. */
  854. public spritesEnabled = true;
  855. // Skeletons
  856. private _skeletonsEnabled = true;
  857. /**
  858. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  859. */
  860. public set skeletonsEnabled(value: boolean) {
  861. if (this._skeletonsEnabled === value) {
  862. return;
  863. }
  864. this._skeletonsEnabled = value;
  865. this.markAllMaterialsAsDirty(Constants.MATERIAL_AttributesDirtyFlag);
  866. }
  867. public get skeletonsEnabled(): boolean {
  868. return this._skeletonsEnabled;
  869. }
  870. // Lens flares
  871. /**
  872. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  873. */
  874. public lensFlaresEnabled = true;
  875. // Collisions
  876. /**
  877. * Gets or sets a boolean indicating if collisions are enabled on this scene
  878. * @see https://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  879. */
  880. public collisionsEnabled = true;
  881. private _collisionCoordinator: ICollisionCoordinator;
  882. /** @hidden */
  883. public get collisionCoordinator(): ICollisionCoordinator {
  884. if (!this._collisionCoordinator) {
  885. this._collisionCoordinator = Scene.CollisionCoordinatorFactory();
  886. this._collisionCoordinator.init(this);
  887. }
  888. return this._collisionCoordinator;
  889. }
  890. /**
  891. * Defines the gravity applied to this scene (used only for collisions)
  892. * @see https://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  893. */
  894. public gravity = new Vector3(0, -9.807, 0);
  895. // Postprocesses
  896. /**
  897. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  898. */
  899. public postProcessesEnabled = true;
  900. /**
  901. * Gets the current postprocess manager
  902. */
  903. public postProcessManager: PostProcessManager;
  904. // Customs render targets
  905. /**
  906. * Gets or sets a boolean indicating if render targets are enabled on this scene
  907. */
  908. public renderTargetsEnabled = true;
  909. /**
  910. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  911. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  912. */
  913. public dumpNextRenderTargets = false;
  914. /**
  915. * The list of user defined render targets added to the scene
  916. */
  917. public customRenderTargets = new Array<RenderTargetTexture>();
  918. /**
  919. * Defines if texture loading must be delayed
  920. * If true, textures will only be loaded when they need to be rendered
  921. */
  922. public useDelayedTextureLoading: boolean;
  923. /**
  924. * Gets the list of meshes imported to the scene through SceneLoader
  925. */
  926. public importedMeshesFiles = new Array<String>();
  927. // Probes
  928. /**
  929. * Gets or sets a boolean indicating if probes are enabled on this scene
  930. */
  931. public probesEnabled = true;
  932. // Offline support
  933. /**
  934. * Gets or sets the current offline provider to use to store scene data
  935. * @see https://doc.babylonjs.com/how_to/caching_resources_in_indexeddb
  936. */
  937. public offlineProvider: IOfflineProvider;
  938. /**
  939. * Gets or sets the action manager associated with the scene
  940. * @see https://doc.babylonjs.com/how_to/how_to_use_actions
  941. */
  942. public actionManager: AbstractActionManager;
  943. private _meshesForIntersections = new SmartArrayNoDuplicate<AbstractMesh>(256);
  944. // Procedural textures
  945. /**
  946. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  947. */
  948. public proceduralTexturesEnabled = true;
  949. // Private
  950. private _engine: Engine;
  951. // Performance counters
  952. private _totalVertices = new PerfCounter();
  953. /** @hidden */
  954. public _activeIndices = new PerfCounter();
  955. /** @hidden */
  956. public _activeParticles = new PerfCounter();
  957. /** @hidden */
  958. public _activeBones = new PerfCounter();
  959. private _animationRatio: number;
  960. /** @hidden */
  961. public _animationTimeLast: number;
  962. /** @hidden */
  963. public _animationTime: number = 0;
  964. /**
  965. * Gets or sets a general scale for animation speed
  966. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  967. */
  968. public animationTimeScale: number = 1;
  969. /** @hidden */
  970. public _cachedMaterial: Nullable<Material>;
  971. /** @hidden */
  972. public _cachedEffect: Nullable<Effect>;
  973. /** @hidden */
  974. public _cachedVisibility: Nullable<number>;
  975. private _renderId = 0;
  976. private _frameId = 0;
  977. private _executeWhenReadyTimeoutId = -1;
  978. private _intermediateRendering = false;
  979. private _viewUpdateFlag = -1;
  980. private _projectionUpdateFlag = -1;
  981. /** @hidden */
  982. public _toBeDisposed = new Array<Nullable<IDisposable>>(256);
  983. private _activeRequests = new Array<IFileRequest>();
  984. /** @hidden */
  985. public _pendingData = new Array();
  986. private _isDisposed = false;
  987. /**
  988. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  989. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  990. */
  991. public dispatchAllSubMeshesOfActiveMeshes: boolean = false;
  992. private _activeMeshes = new SmartArray<AbstractMesh>(256);
  993. private _processedMaterials = new SmartArray<Material>(256);
  994. private _renderTargets = new SmartArrayNoDuplicate<RenderTargetTexture>(256);
  995. /** @hidden */
  996. public _activeParticleSystems = new SmartArray<IParticleSystem>(256);
  997. private _activeSkeletons = new SmartArrayNoDuplicate<Skeleton>(32);
  998. private _softwareSkinnedMeshes = new SmartArrayNoDuplicate<Mesh>(32);
  999. private _renderingManager: RenderingManager;
  1000. /** @hidden */
  1001. public _activeAnimatables = new Array<Animatable>();
  1002. private _transformMatrix = Matrix.Zero();
  1003. private _sceneUbo: UniformBuffer;
  1004. /** @hidden */
  1005. public _viewMatrix: Matrix;
  1006. private _projectionMatrix: Matrix;
  1007. /** @hidden */
  1008. public _forcedViewPosition: Nullable<Vector3>;
  1009. /** @hidden */
  1010. public _frustumPlanes: Plane[];
  1011. /**
  1012. * Gets the list of frustum planes (built from the active camera)
  1013. */
  1014. public get frustumPlanes(): Plane[] {
  1015. return this._frustumPlanes;
  1016. }
  1017. /**
  1018. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  1019. * This is useful if there are more lights that the maximum simulteanous authorized
  1020. */
  1021. public requireLightSorting = false;
  1022. /** @hidden */
  1023. public readonly useMaterialMeshMap: boolean;
  1024. /** @hidden */
  1025. public readonly useClonedMeshMap: boolean;
  1026. private _externalData: StringDictionary<Object>;
  1027. private _uid: Nullable<string>;
  1028. /**
  1029. * @hidden
  1030. * Backing store of defined scene components.
  1031. */
  1032. public _components: ISceneComponent[] = [];
  1033. /**
  1034. * @hidden
  1035. * Backing store of defined scene components.
  1036. */
  1037. public _serializableComponents: ISceneSerializableComponent[] = [];
  1038. /**
  1039. * List of components to register on the next registration step.
  1040. */
  1041. private _transientComponents: ISceneComponent[] = [];
  1042. /**
  1043. * Registers the transient components if needed.
  1044. */
  1045. private _registerTransientComponents(): void {
  1046. // Register components that have been associated lately to the scene.
  1047. if (this._transientComponents.length > 0) {
  1048. for (let component of this._transientComponents) {
  1049. component.register();
  1050. }
  1051. this._transientComponents = [];
  1052. }
  1053. }
  1054. /**
  1055. * @hidden
  1056. * Add a component to the scene.
  1057. * Note that the ccomponent could be registered on th next frame if this is called after
  1058. * the register component stage.
  1059. * @param component Defines the component to add to the scene
  1060. */
  1061. public _addComponent(component: ISceneComponent) {
  1062. this._components.push(component);
  1063. this._transientComponents.push(component);
  1064. const serializableComponent = component as ISceneSerializableComponent;
  1065. if (serializableComponent.addFromContainer && serializableComponent.serialize) {
  1066. this._serializableComponents.push(serializableComponent);
  1067. }
  1068. }
  1069. /**
  1070. * @hidden
  1071. * Gets a component from the scene.
  1072. * @param name defines the name of the component to retrieve
  1073. * @returns the component or null if not present
  1074. */
  1075. public _getComponent(name: string): Nullable<ISceneComponent> {
  1076. for (let component of this._components) {
  1077. if (component.name === name) {
  1078. return component;
  1079. }
  1080. }
  1081. return null;
  1082. }
  1083. /**
  1084. * @hidden
  1085. * Defines the actions happening before camera updates.
  1086. */
  1087. public _beforeCameraUpdateStage = Stage.Create<SimpleStageAction>();
  1088. /**
  1089. * @hidden
  1090. * Defines the actions happening before clear the canvas.
  1091. */
  1092. public _beforeClearStage = Stage.Create<SimpleStageAction>();
  1093. /**
  1094. * @hidden
  1095. * Defines the actions when collecting render targets for the frame.
  1096. */
  1097. public _gatherRenderTargetsStage = Stage.Create<RenderTargetsStageAction>();
  1098. /**
  1099. * @hidden
  1100. * Defines the actions happening for one camera in the frame.
  1101. */
  1102. public _gatherActiveCameraRenderTargetsStage = Stage.Create<RenderTargetsStageAction>();
  1103. /**
  1104. * @hidden
  1105. * Defines the actions happening during the per mesh ready checks.
  1106. */
  1107. public _isReadyForMeshStage = Stage.Create<MeshStageAction>();
  1108. /**
  1109. * @hidden
  1110. * Defines the actions happening before evaluate active mesh checks.
  1111. */
  1112. public _beforeEvaluateActiveMeshStage = Stage.Create<SimpleStageAction>();
  1113. /**
  1114. * @hidden
  1115. * Defines the actions happening during the evaluate sub mesh checks.
  1116. */
  1117. public _evaluateSubMeshStage = Stage.Create<EvaluateSubMeshStageAction>();
  1118. /**
  1119. * @hidden
  1120. * Defines the actions happening during the active mesh stage.
  1121. */
  1122. public _preActiveMeshStage = Stage.Create<PreActiveMeshStageAction>();
  1123. /**
  1124. * @hidden
  1125. * Defines the actions happening during the per camera render target step.
  1126. */
  1127. public _cameraDrawRenderTargetStage = Stage.Create<CameraStageFrameBufferAction>();
  1128. /**
  1129. * @hidden
  1130. * Defines the actions happening just before the active camera is drawing.
  1131. */
  1132. public _beforeCameraDrawStage = Stage.Create<CameraStageAction>();
  1133. /**
  1134. * @hidden
  1135. * Defines the actions happening just before a render target is drawing.
  1136. */
  1137. public _beforeRenderTargetDrawStage = Stage.Create<RenderTargetStageAction>();
  1138. /**
  1139. * @hidden
  1140. * Defines the actions happening just before a rendering group is drawing.
  1141. */
  1142. public _beforeRenderingGroupDrawStage = Stage.Create<RenderingGroupStageAction>();
  1143. /**
  1144. * @hidden
  1145. * Defines the actions happening just before a mesh is drawing.
  1146. */
  1147. public _beforeRenderingMeshStage = Stage.Create<RenderingMeshStageAction>();
  1148. /**
  1149. * @hidden
  1150. * Defines the actions happening just after a mesh has been drawn.
  1151. */
  1152. public _afterRenderingMeshStage = Stage.Create<RenderingMeshStageAction>();
  1153. /**
  1154. * @hidden
  1155. * Defines the actions happening just after a rendering group has been drawn.
  1156. */
  1157. public _afterRenderingGroupDrawStage = Stage.Create<RenderingGroupStageAction>();
  1158. /**
  1159. * @hidden
  1160. * Defines the actions happening just after the active camera has been drawn.
  1161. */
  1162. public _afterCameraDrawStage = Stage.Create<CameraStageAction>();
  1163. /**
  1164. * @hidden
  1165. * Defines the actions happening just after a render target has been drawn.
  1166. */
  1167. public _afterRenderTargetDrawStage = Stage.Create<RenderTargetStageAction>();
  1168. /**
  1169. * @hidden
  1170. * Defines the actions happening just after rendering all cameras and computing intersections.
  1171. */
  1172. public _afterRenderStage = Stage.Create<SimpleStageAction>();
  1173. /**
  1174. * @hidden
  1175. * Defines the actions happening when a pointer move event happens.
  1176. */
  1177. public _pointerMoveStage = Stage.Create<PointerMoveStageAction>();
  1178. /**
  1179. * @hidden
  1180. * Defines the actions happening when a pointer down event happens.
  1181. */
  1182. public _pointerDownStage = Stage.Create<PointerUpDownStageAction>();
  1183. /**
  1184. * @hidden
  1185. * Defines the actions happening when a pointer up event happens.
  1186. */
  1187. public _pointerUpStage = Stage.Create<PointerUpDownStageAction>();
  1188. /**
  1189. * an optional map from Geometry Id to Geometry index in the 'geometries' array
  1190. */
  1191. private geometriesByUniqueId: Nullable<{ [uniqueId: string]: number | undefined }> = null;
  1192. /**
  1193. * Creates a new Scene
  1194. * @param engine defines the engine to use to render this scene
  1195. * @param options defines the scene options
  1196. */
  1197. constructor(engine: Engine, options?: SceneOptions) {
  1198. super();
  1199. const fullOptions = {
  1200. useGeometryUniqueIdsMap: true,
  1201. useMaterialMeshMap: true,
  1202. useClonedMeshMap: true,
  1203. virtual: false,
  1204. ...options
  1205. };
  1206. this._engine = engine || EngineStore.LastCreatedEngine;
  1207. if (!fullOptions.virtual) {
  1208. EngineStore._LastCreatedScene = this;
  1209. this._engine.scenes.push(this);
  1210. }
  1211. this._uid = null;
  1212. this._renderingManager = new RenderingManager(this);
  1213. if (PostProcessManager) {
  1214. this.postProcessManager = new PostProcessManager(this);
  1215. }
  1216. if (DomManagement.IsWindowObjectExist()) {
  1217. this.attachControl();
  1218. }
  1219. // Uniform Buffer
  1220. this._createUbo();
  1221. // Default Image processing definition
  1222. if (ImageProcessingConfiguration) {
  1223. this._imageProcessingConfiguration = new ImageProcessingConfiguration();
  1224. }
  1225. this.setDefaultCandidateProviders();
  1226. if (fullOptions.useGeometryUniqueIdsMap) {
  1227. this.geometriesByUniqueId = {};
  1228. }
  1229. this.useMaterialMeshMap = fullOptions.useMaterialMeshMap;
  1230. this.useClonedMeshMap = fullOptions.useClonedMeshMap;
  1231. if (!options || !options.virtual) {
  1232. this._engine.onNewSceneAddedObservable.notifyObservers(this);
  1233. }
  1234. }
  1235. /**
  1236. * Gets a string identifying the name of the class
  1237. * @returns "Scene" string
  1238. */
  1239. public getClassName(): string {
  1240. return "Scene";
  1241. }
  1242. private _defaultMeshCandidates: ISmartArrayLike<AbstractMesh> = {
  1243. data: [],
  1244. length: 0
  1245. };
  1246. /**
  1247. * @hidden
  1248. */
  1249. public _getDefaultMeshCandidates(): ISmartArrayLike<AbstractMesh> {
  1250. this._defaultMeshCandidates.data = this.meshes;
  1251. this._defaultMeshCandidates.length = this.meshes.length;
  1252. return this._defaultMeshCandidates;
  1253. }
  1254. private _defaultSubMeshCandidates: ISmartArrayLike<SubMesh> = {
  1255. data: [],
  1256. length: 0
  1257. };
  1258. /**
  1259. * @hidden
  1260. */
  1261. public _getDefaultSubMeshCandidates(mesh: AbstractMesh): ISmartArrayLike<SubMesh> {
  1262. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  1263. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  1264. return this._defaultSubMeshCandidates;
  1265. }
  1266. /**
  1267. * Sets the default candidate providers for the scene.
  1268. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  1269. * and getCollidingSubMeshCandidates to their default function
  1270. */
  1271. public setDefaultCandidateProviders(): void {
  1272. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  1273. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1274. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1275. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  1276. }
  1277. /**
  1278. * Gets the mesh that is currently under the pointer
  1279. */
  1280. public get meshUnderPointer(): Nullable<AbstractMesh> {
  1281. return this._inputManager.meshUnderPointer;
  1282. }
  1283. /**
  1284. * Gets or sets the current on-screen X position of the pointer
  1285. */
  1286. public get pointerX(): number {
  1287. return this._inputManager.pointerX;
  1288. }
  1289. public set pointerX(value: number) {
  1290. this._inputManager.pointerX = value;
  1291. }
  1292. /**
  1293. * Gets or sets the current on-screen Y position of the pointer
  1294. */
  1295. public get pointerY(): number {
  1296. return this._inputManager.pointerY;
  1297. }
  1298. public set pointerY(value: number) {
  1299. this._inputManager.pointerY = value;
  1300. }
  1301. /**
  1302. * Gets the cached material (ie. the latest rendered one)
  1303. * @returns the cached material
  1304. */
  1305. public getCachedMaterial(): Nullable<Material> {
  1306. return this._cachedMaterial;
  1307. }
  1308. /**
  1309. * Gets the cached effect (ie. the latest rendered one)
  1310. * @returns the cached effect
  1311. */
  1312. public getCachedEffect(): Nullable<Effect> {
  1313. return this._cachedEffect;
  1314. }
  1315. /**
  1316. * Gets the cached visibility state (ie. the latest rendered one)
  1317. * @returns the cached visibility state
  1318. */
  1319. public getCachedVisibility(): Nullable<number> {
  1320. return this._cachedVisibility;
  1321. }
  1322. /**
  1323. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  1324. * @param material defines the current material
  1325. * @param effect defines the current effect
  1326. * @param visibility defines the current visibility state
  1327. * @returns true if one parameter is not cached
  1328. */
  1329. public isCachedMaterialInvalid(material: Material, effect: Effect, visibility: number = 1) {
  1330. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  1331. }
  1332. /**
  1333. * Gets the engine associated with the scene
  1334. * @returns an Engine
  1335. */
  1336. public getEngine(): Engine {
  1337. return this._engine;
  1338. }
  1339. /**
  1340. * Gets the total number of vertices rendered per frame
  1341. * @returns the total number of vertices rendered per frame
  1342. */
  1343. public getTotalVertices(): number {
  1344. return this._totalVertices.current;
  1345. }
  1346. /**
  1347. * Gets the performance counter for total vertices
  1348. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1349. */
  1350. public get totalVerticesPerfCounter(): PerfCounter {
  1351. return this._totalVertices;
  1352. }
  1353. /**
  1354. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  1355. * @returns the total number of active indices rendered per frame
  1356. */
  1357. public getActiveIndices(): number {
  1358. return this._activeIndices.current;
  1359. }
  1360. /**
  1361. * Gets the performance counter for active indices
  1362. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1363. */
  1364. public get totalActiveIndicesPerfCounter(): PerfCounter {
  1365. return this._activeIndices;
  1366. }
  1367. /**
  1368. * Gets the total number of active particles rendered per frame
  1369. * @returns the total number of active particles rendered per frame
  1370. */
  1371. public getActiveParticles(): number {
  1372. return this._activeParticles.current;
  1373. }
  1374. /**
  1375. * Gets the performance counter for active particles
  1376. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1377. */
  1378. public get activeParticlesPerfCounter(): PerfCounter {
  1379. return this._activeParticles;
  1380. }
  1381. /**
  1382. * Gets the total number of active bones rendered per frame
  1383. * @returns the total number of active bones rendered per frame
  1384. */
  1385. public getActiveBones(): number {
  1386. return this._activeBones.current;
  1387. }
  1388. /**
  1389. * Gets the performance counter for active bones
  1390. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  1391. */
  1392. public get activeBonesPerfCounter(): PerfCounter {
  1393. return this._activeBones;
  1394. }
  1395. /**
  1396. * Gets the array of active meshes
  1397. * @returns an array of AbstractMesh
  1398. */
  1399. public getActiveMeshes(): SmartArray<AbstractMesh> {
  1400. return this._activeMeshes;
  1401. }
  1402. /**
  1403. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  1404. * @returns a number
  1405. */
  1406. public getAnimationRatio(): number {
  1407. return this._animationRatio !== undefined ? this._animationRatio : 1;
  1408. }
  1409. /**
  1410. * Gets an unique Id for the current render phase
  1411. * @returns a number
  1412. */
  1413. public getRenderId(): number {
  1414. return this._renderId;
  1415. }
  1416. /**
  1417. * Gets an unique Id for the current frame
  1418. * @returns a number
  1419. */
  1420. public getFrameId(): number {
  1421. return this._frameId;
  1422. }
  1423. /** Call this function if you want to manually increment the render Id*/
  1424. public incrementRenderId(): void {
  1425. this._renderId++;
  1426. }
  1427. private _createUbo(): void {
  1428. this._sceneUbo = new UniformBuffer(this._engine, undefined, true);
  1429. this._sceneUbo.addUniform("viewProjection", 16);
  1430. this._sceneUbo.addUniform("view", 16);
  1431. }
  1432. /**
  1433. * Use this method to simulate a pointer move on a mesh
  1434. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1435. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1436. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1437. * @returns the current scene
  1438. */
  1439. public simulatePointerMove(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1440. this._inputManager.simulatePointerMove(pickResult, pointerEventInit);
  1441. return this;
  1442. }
  1443. /**
  1444. * Use this method to simulate a pointer down on a mesh
  1445. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1446. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1447. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1448. * @returns the current scene
  1449. */
  1450. public simulatePointerDown(pickResult: PickingInfo, pointerEventInit?: PointerEventInit): Scene {
  1451. this._inputManager.simulatePointerDown(pickResult, pointerEventInit);
  1452. return this;
  1453. }
  1454. /**
  1455. * Use this method to simulate a pointer up on a mesh
  1456. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  1457. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  1458. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  1459. * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default)
  1460. * @returns the current scene
  1461. */
  1462. public simulatePointerUp(pickResult: PickingInfo, pointerEventInit?: PointerEventInit, doubleTap?: boolean): Scene {
  1463. this._inputManager.simulatePointerUp(pickResult, pointerEventInit, doubleTap);
  1464. return this;
  1465. }
  1466. /**
  1467. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  1468. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  1469. * @returns true if the pointer was captured
  1470. */
  1471. public isPointerCaptured(pointerId = 0): boolean {
  1472. return this._inputManager.isPointerCaptured(pointerId);
  1473. }
  1474. /**
  1475. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  1476. * @param attachUp defines if you want to attach events to pointerup
  1477. * @param attachDown defines if you want to attach events to pointerdown
  1478. * @param attachMove defines if you want to attach events to pointermove
  1479. */
  1480. public attachControl(attachUp = true, attachDown = true, attachMove = true): void {
  1481. this._inputManager.attachControl(attachUp, attachDown, attachMove);
  1482. }
  1483. /** Detaches all event handlers*/
  1484. public detachControl() {
  1485. this._inputManager.detachControl();
  1486. }
  1487. /**
  1488. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  1489. * Delay loaded resources are not taking in account
  1490. * @return true if all required resources are ready
  1491. */
  1492. public isReady(): boolean {
  1493. if (this._isDisposed) {
  1494. return false;
  1495. }
  1496. let index: number;
  1497. let engine = this.getEngine();
  1498. // Effects
  1499. if (!engine.areAllEffectsReady()) {
  1500. return false;
  1501. }
  1502. // Pending data
  1503. if (this._pendingData.length > 0) {
  1504. return false;
  1505. }
  1506. // Meshes
  1507. for (index = 0; index < this.meshes.length; index++) {
  1508. var mesh = this.meshes[index];
  1509. if (!mesh.isEnabled()) {
  1510. continue;
  1511. }
  1512. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  1513. continue;
  1514. }
  1515. if (!mesh.isReady(true)) {
  1516. return false;
  1517. }
  1518. let hardwareInstancedRendering = mesh.hasThinInstances || mesh.getClassName() === "InstancedMesh" || mesh.getClassName() === "InstancedLinesMesh" || engine.getCaps().instancedArrays && (<Mesh>mesh).instances.length > 0;
  1519. // Is Ready For Mesh
  1520. for (let step of this._isReadyForMeshStage) {
  1521. if (!step.action(mesh, hardwareInstancedRendering)) {
  1522. return false;
  1523. }
  1524. }
  1525. }
  1526. // Geometries
  1527. for (index = 0; index < this.geometries.length; index++) {
  1528. var geometry = this.geometries[index];
  1529. if (geometry.delayLoadState === Constants.DELAYLOADSTATE_LOADING) {
  1530. return false;
  1531. }
  1532. }
  1533. // Post-processes
  1534. if (this.activeCameras && this.activeCameras.length > 0) {
  1535. for (var camera of this.activeCameras) {
  1536. if (!camera.isReady(true)) {
  1537. return false;
  1538. }
  1539. }
  1540. } else if (this.activeCamera) {
  1541. if (!this.activeCamera.isReady(true)) {
  1542. return false;
  1543. }
  1544. }
  1545. // Particles
  1546. for (var particleSystem of this.particleSystems) {
  1547. if (!particleSystem.isReady()) {
  1548. return false;
  1549. }
  1550. }
  1551. return true;
  1552. }
  1553. /** Resets all cached information relative to material (including effect and visibility) */
  1554. public resetCachedMaterial(): void {
  1555. this._cachedMaterial = null;
  1556. this._cachedEffect = null;
  1557. this._cachedVisibility = null;
  1558. }
  1559. /**
  1560. * Registers a function to be called before every frame render
  1561. * @param func defines the function to register
  1562. */
  1563. public registerBeforeRender(func: () => void): void {
  1564. this.onBeforeRenderObservable.add(func);
  1565. }
  1566. /**
  1567. * Unregisters a function called before every frame render
  1568. * @param func defines the function to unregister
  1569. */
  1570. public unregisterBeforeRender(func: () => void): void {
  1571. this.onBeforeRenderObservable.removeCallback(func);
  1572. }
  1573. /**
  1574. * Registers a function to be called after every frame render
  1575. * @param func defines the function to register
  1576. */
  1577. public registerAfterRender(func: () => void): void {
  1578. this.onAfterRenderObservable.add(func);
  1579. }
  1580. /**
  1581. * Unregisters a function called after every frame render
  1582. * @param func defines the function to unregister
  1583. */
  1584. public unregisterAfterRender(func: () => void): void {
  1585. this.onAfterRenderObservable.removeCallback(func);
  1586. }
  1587. private _executeOnceBeforeRender(func: () => void): void {
  1588. let execFunc = () => {
  1589. func();
  1590. setTimeout(() => {
  1591. this.unregisterBeforeRender(execFunc);
  1592. });
  1593. };
  1594. this.registerBeforeRender(execFunc);
  1595. }
  1596. /**
  1597. * The provided function will run before render once and will be disposed afterwards.
  1598. * A timeout delay can be provided so that the function will be executed in N ms.
  1599. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  1600. * @param func The function to be executed.
  1601. * @param timeout optional delay in ms
  1602. */
  1603. public executeOnceBeforeRender(func: () => void, timeout?: number): void {
  1604. if (timeout !== undefined) {
  1605. setTimeout(() => {
  1606. this._executeOnceBeforeRender(func);
  1607. }, timeout);
  1608. } else {
  1609. this._executeOnceBeforeRender(func);
  1610. }
  1611. }
  1612. /** @hidden */
  1613. public _addPendingData(data: any): void {
  1614. this._pendingData.push(data);
  1615. }
  1616. /** @hidden */
  1617. public _removePendingData(data: any): void {
  1618. var wasLoading = this.isLoading;
  1619. var index = this._pendingData.indexOf(data);
  1620. if (index !== -1) {
  1621. this._pendingData.splice(index, 1);
  1622. }
  1623. if (wasLoading && !this.isLoading) {
  1624. this.onDataLoadedObservable.notifyObservers(this);
  1625. }
  1626. }
  1627. /**
  1628. * Returns the number of items waiting to be loaded
  1629. * @returns the number of items waiting to be loaded
  1630. */
  1631. public getWaitingItemsCount(): number {
  1632. return this._pendingData.length;
  1633. }
  1634. /**
  1635. * Returns a boolean indicating if the scene is still loading data
  1636. */
  1637. public get isLoading(): boolean {
  1638. return this._pendingData.length > 0;
  1639. }
  1640. /**
  1641. * Registers a function to be executed when the scene is ready
  1642. * @param {Function} func - the function to be executed
  1643. */
  1644. public executeWhenReady(func: () => void): void {
  1645. this.onReadyObservable.add(func);
  1646. if (this._executeWhenReadyTimeoutId !== -1) {
  1647. return;
  1648. }
  1649. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1650. this._checkIsReady();
  1651. }, 150);
  1652. }
  1653. /**
  1654. * Returns a promise that resolves when the scene is ready
  1655. * @returns A promise that resolves when the scene is ready
  1656. */
  1657. public whenReadyAsync(): Promise<void> {
  1658. return new Promise((resolve) => {
  1659. this.executeWhenReady(() => {
  1660. resolve();
  1661. });
  1662. });
  1663. }
  1664. /** @hidden */
  1665. public _checkIsReady() {
  1666. this._registerTransientComponents();
  1667. if (this.isReady()) {
  1668. this.onReadyObservable.notifyObservers(this);
  1669. this.onReadyObservable.clear();
  1670. this._executeWhenReadyTimeoutId = -1;
  1671. return;
  1672. }
  1673. if (this._isDisposed) {
  1674. this.onReadyObservable.clear();
  1675. this._executeWhenReadyTimeoutId = -1;
  1676. return;
  1677. }
  1678. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1679. this._checkIsReady();
  1680. }, 150);
  1681. }
  1682. /**
  1683. * Gets all animatable attached to the scene
  1684. */
  1685. public get animatables(): Animatable[] {
  1686. return this._activeAnimatables;
  1687. }
  1688. /**
  1689. * Resets the last animation time frame.
  1690. * Useful to override when animations start running when loading a scene for the first time.
  1691. */
  1692. public resetLastAnimationTimeFrame(): void {
  1693. this._animationTimeLast = PrecisionDate.Now;
  1694. }
  1695. // Matrix
  1696. /**
  1697. * Gets the current view matrix
  1698. * @returns a Matrix
  1699. */
  1700. public getViewMatrix(): Matrix {
  1701. return this._viewMatrix;
  1702. }
  1703. /**
  1704. * Gets the current projection matrix
  1705. * @returns a Matrix
  1706. */
  1707. public getProjectionMatrix(): Matrix {
  1708. return this._projectionMatrix;
  1709. }
  1710. /**
  1711. * Gets the current transform matrix
  1712. * @returns a Matrix made of View * Projection
  1713. */
  1714. public getTransformMatrix(): Matrix {
  1715. return this._transformMatrix;
  1716. }
  1717. /**
  1718. * Sets the current transform matrix
  1719. * @param viewL defines the View matrix to use
  1720. * @param projectionL defines the Projection matrix to use
  1721. * @param viewR defines the right View matrix to use (if provided)
  1722. * @param projectionR defines the right Projection matrix to use (if provided)
  1723. */
  1724. public setTransformMatrix(viewL: Matrix, projectionL: Matrix, viewR?: Matrix, projectionR?: Matrix): void {
  1725. if (this._viewUpdateFlag === viewL.updateFlag && this._projectionUpdateFlag === projectionL.updateFlag) {
  1726. return;
  1727. }
  1728. this._viewUpdateFlag = viewL.updateFlag;
  1729. this._projectionUpdateFlag = projectionL.updateFlag;
  1730. this._viewMatrix = viewL;
  1731. this._projectionMatrix = projectionL;
  1732. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  1733. // Update frustum
  1734. if (!this._frustumPlanes) {
  1735. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  1736. } else {
  1737. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1738. }
  1739. if (this._multiviewSceneUbo && this._multiviewSceneUbo.useUbo) {
  1740. this._updateMultiviewUbo(viewR, projectionR);
  1741. } else if (this._sceneUbo.useUbo) {
  1742. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  1743. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  1744. this._sceneUbo.update();
  1745. }
  1746. }
  1747. /**
  1748. * Gets the uniform buffer used to store scene data
  1749. * @returns a UniformBuffer
  1750. */
  1751. public getSceneUniformBuffer(): UniformBuffer {
  1752. return this._multiviewSceneUbo ? this._multiviewSceneUbo : this._sceneUbo;
  1753. }
  1754. /**
  1755. * Gets an unique (relatively to the current scene) Id
  1756. * @returns an unique number for the scene
  1757. */
  1758. public getUniqueId() {
  1759. return UniqueIdGenerator.UniqueId;
  1760. }
  1761. /**
  1762. * Add a mesh to the list of scene's meshes
  1763. * @param newMesh defines the mesh to add
  1764. * @param recursive if all child meshes should also be added to the scene
  1765. */
  1766. public addMesh(newMesh: AbstractMesh, recursive = false) {
  1767. if (this._blockEntityCollection) {
  1768. return;
  1769. }
  1770. this.meshes.push(newMesh);
  1771. newMesh._resyncLightSources();
  1772. if (!newMesh.parent) {
  1773. newMesh._addToSceneRootNodes();
  1774. }
  1775. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  1776. if (recursive) {
  1777. newMesh.getChildMeshes().forEach((m) => {
  1778. this.addMesh(m);
  1779. });
  1780. }
  1781. }
  1782. /**
  1783. * Remove a mesh for the list of scene's meshes
  1784. * @param toRemove defines the mesh to remove
  1785. * @param recursive if all child meshes should also be removed from the scene
  1786. * @returns the index where the mesh was in the mesh list
  1787. */
  1788. public removeMesh(toRemove: AbstractMesh, recursive = false): number {
  1789. var index = this.meshes.indexOf(toRemove);
  1790. if (index !== -1) {
  1791. // Remove from the scene if mesh found
  1792. this.meshes[index] = this.meshes[this.meshes.length - 1];
  1793. this.meshes.pop();
  1794. if (!toRemove.parent) {
  1795. toRemove._removeFromSceneRootNodes();
  1796. }
  1797. }
  1798. this.onMeshRemovedObservable.notifyObservers(toRemove);
  1799. if (recursive) {
  1800. toRemove.getChildMeshes().forEach((m) => {
  1801. this.removeMesh(m);
  1802. });
  1803. }
  1804. return index;
  1805. }
  1806. /**
  1807. * Add a transform node to the list of scene's transform nodes
  1808. * @param newTransformNode defines the transform node to add
  1809. */
  1810. public addTransformNode(newTransformNode: TransformNode) {
  1811. if (this._blockEntityCollection) {
  1812. return;
  1813. }
  1814. newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
  1815. this.transformNodes.push(newTransformNode);
  1816. if (!newTransformNode.parent) {
  1817. newTransformNode._addToSceneRootNodes();
  1818. }
  1819. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  1820. }
  1821. /**
  1822. * Remove a transform node for the list of scene's transform nodes
  1823. * @param toRemove defines the transform node to remove
  1824. * @returns the index where the transform node was in the transform node list
  1825. */
  1826. public removeTransformNode(toRemove: TransformNode): number {
  1827. var index = toRemove._indexInSceneTransformNodesArray;
  1828. if (index !== -1) {
  1829. if (index !== this.transformNodes.length - 1) {
  1830. const lastNode = this.transformNodes[this.transformNodes.length - 1];
  1831. this.transformNodes[index] = lastNode;
  1832. lastNode._indexInSceneTransformNodesArray = index;
  1833. }
  1834. toRemove._indexInSceneTransformNodesArray = -1;
  1835. this.transformNodes.pop();
  1836. if (!toRemove.parent) {
  1837. toRemove._removeFromSceneRootNodes();
  1838. }
  1839. }
  1840. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  1841. return index;
  1842. }
  1843. /**
  1844. * Remove a skeleton for the list of scene's skeletons
  1845. * @param toRemove defines the skeleton to remove
  1846. * @returns the index where the skeleton was in the skeleton list
  1847. */
  1848. public removeSkeleton(toRemove: Skeleton): number {
  1849. var index = this.skeletons.indexOf(toRemove);
  1850. if (index !== -1) {
  1851. // Remove from the scene if found
  1852. this.skeletons.splice(index, 1);
  1853. this.onSkeletonRemovedObservable.notifyObservers(toRemove);
  1854. }
  1855. return index;
  1856. }
  1857. /**
  1858. * Remove a morph target for the list of scene's morph targets
  1859. * @param toRemove defines the morph target to remove
  1860. * @returns the index where the morph target was in the morph target list
  1861. */
  1862. public removeMorphTargetManager(toRemove: MorphTargetManager): number {
  1863. var index = this.morphTargetManagers.indexOf(toRemove);
  1864. if (index !== -1) {
  1865. // Remove from the scene if found
  1866. this.morphTargetManagers.splice(index, 1);
  1867. }
  1868. return index;
  1869. }
  1870. /**
  1871. * Remove a light for the list of scene's lights
  1872. * @param toRemove defines the light to remove
  1873. * @returns the index where the light was in the light list
  1874. */
  1875. public removeLight(toRemove: Light): number {
  1876. var index = this.lights.indexOf(toRemove);
  1877. if (index !== -1) {
  1878. // Remove from meshes
  1879. for (var mesh of this.meshes) {
  1880. mesh._removeLightSource(toRemove, false);
  1881. }
  1882. // Remove from the scene if mesh found
  1883. this.lights.splice(index, 1);
  1884. this.sortLightsByPriority();
  1885. if (!toRemove.parent) {
  1886. toRemove._removeFromSceneRootNodes();
  1887. }
  1888. }
  1889. this.onLightRemovedObservable.notifyObservers(toRemove);
  1890. return index;
  1891. }
  1892. /**
  1893. * Remove a camera for the list of scene's cameras
  1894. * @param toRemove defines the camera to remove
  1895. * @returns the index where the camera was in the camera list
  1896. */
  1897. public removeCamera(toRemove: Camera): number {
  1898. var index = this.cameras.indexOf(toRemove);
  1899. if (index !== -1) {
  1900. // Remove from the scene if mesh found
  1901. this.cameras.splice(index, 1);
  1902. if (!toRemove.parent) {
  1903. toRemove._removeFromSceneRootNodes();
  1904. }
  1905. }
  1906. // Remove from activeCameras
  1907. var index2 = this.activeCameras.indexOf(toRemove);
  1908. if (index2 !== -1) {
  1909. // Remove from the scene if mesh found
  1910. this.activeCameras.splice(index2, 1);
  1911. }
  1912. // Reset the activeCamera
  1913. if (this.activeCamera === toRemove) {
  1914. if (this.cameras.length > 0) {
  1915. this.activeCamera = this.cameras[0];
  1916. } else {
  1917. this.activeCamera = null;
  1918. }
  1919. }
  1920. this.onCameraRemovedObservable.notifyObservers(toRemove);
  1921. return index;
  1922. }
  1923. /**
  1924. * Remove a particle system for the list of scene's particle systems
  1925. * @param toRemove defines the particle system to remove
  1926. * @returns the index where the particle system was in the particle system list
  1927. */
  1928. public removeParticleSystem(toRemove: IParticleSystem): number {
  1929. var index = this.particleSystems.indexOf(toRemove);
  1930. if (index !== -1) {
  1931. this.particleSystems.splice(index, 1);
  1932. }
  1933. return index;
  1934. }
  1935. /**
  1936. * Remove a animation for the list of scene's animations
  1937. * @param toRemove defines the animation to remove
  1938. * @returns the index where the animation was in the animation list
  1939. */
  1940. public removeAnimation(toRemove: Animation): number {
  1941. var index = this.animations.indexOf(toRemove);
  1942. if (index !== -1) {
  1943. this.animations.splice(index, 1);
  1944. }
  1945. return index;
  1946. }
  1947. /**
  1948. * Will stop the animation of the given target
  1949. * @param target - the target
  1950. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  1951. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  1952. */
  1953. public stopAnimation(target: any, animationName?: string, targetMask?: (target: any) => boolean): void {
  1954. // Do nothing as code will be provided by animation component
  1955. }
  1956. /**
  1957. * Removes the given animation group from this scene.
  1958. * @param toRemove The animation group to remove
  1959. * @returns The index of the removed animation group
  1960. */
  1961. public removeAnimationGroup(toRemove: AnimationGroup): number {
  1962. var index = this.animationGroups.indexOf(toRemove);
  1963. if (index !== -1) {
  1964. this.animationGroups.splice(index, 1);
  1965. }
  1966. return index;
  1967. }
  1968. /**
  1969. * Removes the given multi-material from this scene.
  1970. * @param toRemove The multi-material to remove
  1971. * @returns The index of the removed multi-material
  1972. */
  1973. public removeMultiMaterial(toRemove: MultiMaterial): number {
  1974. var index = this.multiMaterials.indexOf(toRemove);
  1975. if (index !== -1) {
  1976. this.multiMaterials.splice(index, 1);
  1977. }
  1978. return index;
  1979. }
  1980. /**
  1981. * Removes the given material from this scene.
  1982. * @param toRemove The material to remove
  1983. * @returns The index of the removed material
  1984. */
  1985. public removeMaterial(toRemove: Material): number {
  1986. var index = toRemove._indexInSceneMaterialArray;
  1987. if (index !== -1 && index < this.materials.length) {
  1988. if (index !== this.materials.length - 1) {
  1989. const lastMaterial = this.materials[this.materials.length - 1];
  1990. this.materials[index] = lastMaterial;
  1991. lastMaterial._indexInSceneMaterialArray = index;
  1992. }
  1993. toRemove._indexInSceneMaterialArray = -1;
  1994. this.materials.pop();
  1995. }
  1996. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  1997. return index;
  1998. }
  1999. /**
  2000. * Removes the given action manager from this scene.
  2001. * @param toRemove The action manager to remove
  2002. * @returns The index of the removed action manager
  2003. */
  2004. public removeActionManager(toRemove: AbstractActionManager): number {
  2005. var index = this.actionManagers.indexOf(toRemove);
  2006. if (index !== -1) {
  2007. this.actionManagers.splice(index, 1);
  2008. }
  2009. return index;
  2010. }
  2011. /**
  2012. * Removes the given texture from this scene.
  2013. * @param toRemove The texture to remove
  2014. * @returns The index of the removed texture
  2015. */
  2016. public removeTexture(toRemove: BaseTexture): number {
  2017. var index = this.textures.indexOf(toRemove);
  2018. if (index !== -1) {
  2019. this.textures.splice(index, 1);
  2020. }
  2021. this.onTextureRemovedObservable.notifyObservers(toRemove);
  2022. return index;
  2023. }
  2024. /**
  2025. * Adds the given light to this scene
  2026. * @param newLight The light to add
  2027. */
  2028. public addLight(newLight: Light): void {
  2029. if (this._blockEntityCollection) {
  2030. return;
  2031. }
  2032. this.lights.push(newLight);
  2033. this.sortLightsByPriority();
  2034. if (!newLight.parent) {
  2035. newLight._addToSceneRootNodes();
  2036. }
  2037. // Add light to all meshes (To support if the light is removed and then re-added)
  2038. for (var mesh of this.meshes) {
  2039. if (mesh.lightSources.indexOf(newLight) === -1) {
  2040. mesh.lightSources.push(newLight);
  2041. mesh._resyncLightSources();
  2042. }
  2043. }
  2044. this.onNewLightAddedObservable.notifyObservers(newLight);
  2045. }
  2046. /**
  2047. * Sorts the list list based on light priorities
  2048. */
  2049. public sortLightsByPriority(): void {
  2050. if (this.requireLightSorting) {
  2051. this.lights.sort(Light.CompareLightsPriority);
  2052. }
  2053. }
  2054. /**
  2055. * Adds the given camera to this scene
  2056. * @param newCamera The camera to add
  2057. */
  2058. public addCamera(newCamera: Camera): void {
  2059. if (this._blockEntityCollection) {
  2060. return;
  2061. }
  2062. this.cameras.push(newCamera);
  2063. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  2064. if (!newCamera.parent) {
  2065. newCamera._addToSceneRootNodes();
  2066. }
  2067. }
  2068. /**
  2069. * Adds the given skeleton to this scene
  2070. * @param newSkeleton The skeleton to add
  2071. */
  2072. public addSkeleton(newSkeleton: Skeleton): void {
  2073. if (this._blockEntityCollection) {
  2074. return;
  2075. }
  2076. this.skeletons.push(newSkeleton);
  2077. this.onNewSkeletonAddedObservable.notifyObservers(newSkeleton);
  2078. }
  2079. /**
  2080. * Adds the given particle system to this scene
  2081. * @param newParticleSystem The particle system to add
  2082. */
  2083. public addParticleSystem(newParticleSystem: IParticleSystem): void {
  2084. if (this._blockEntityCollection) {
  2085. return;
  2086. }
  2087. this.particleSystems.push(newParticleSystem);
  2088. }
  2089. /**
  2090. * Adds the given animation to this scene
  2091. * @param newAnimation The animation to add
  2092. */
  2093. public addAnimation(newAnimation: Animation): void {
  2094. if (this._blockEntityCollection) {
  2095. return;
  2096. }
  2097. this.animations.push(newAnimation);
  2098. }
  2099. /**
  2100. * Adds the given animation group to this scene.
  2101. * @param newAnimationGroup The animation group to add
  2102. */
  2103. public addAnimationGroup(newAnimationGroup: AnimationGroup): void {
  2104. if (this._blockEntityCollection) {
  2105. return;
  2106. }
  2107. this.animationGroups.push(newAnimationGroup);
  2108. }
  2109. /**
  2110. * Adds the given multi-material to this scene
  2111. * @param newMultiMaterial The multi-material to add
  2112. */
  2113. public addMultiMaterial(newMultiMaterial: MultiMaterial): void {
  2114. if (this._blockEntityCollection) {
  2115. return;
  2116. }
  2117. this.multiMaterials.push(newMultiMaterial);
  2118. }
  2119. /**
  2120. * Adds the given material to this scene
  2121. * @param newMaterial The material to add
  2122. */
  2123. public addMaterial(newMaterial: Material): void {
  2124. if (this._blockEntityCollection) {
  2125. return;
  2126. }
  2127. newMaterial._indexInSceneMaterialArray = this.materials.length;
  2128. this.materials.push(newMaterial);
  2129. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  2130. }
  2131. /**
  2132. * Adds the given morph target to this scene
  2133. * @param newMorphTargetManager The morph target to add
  2134. */
  2135. public addMorphTargetManager(newMorphTargetManager: MorphTargetManager): void {
  2136. if (this._blockEntityCollection) {
  2137. return;
  2138. }
  2139. this.morphTargetManagers.push(newMorphTargetManager);
  2140. }
  2141. /**
  2142. * Adds the given geometry to this scene
  2143. * @param newGeometry The geometry to add
  2144. */
  2145. public addGeometry(newGeometry: Geometry): void {
  2146. if (this._blockEntityCollection) {
  2147. return;
  2148. }
  2149. if (this.geometriesByUniqueId) {
  2150. this.geometriesByUniqueId[newGeometry.uniqueId] = this.geometries.length;
  2151. }
  2152. this.geometries.push(newGeometry);
  2153. }
  2154. /**
  2155. * Adds the given action manager to this scene
  2156. * @param newActionManager The action manager to add
  2157. */
  2158. public addActionManager(newActionManager: AbstractActionManager): void {
  2159. this.actionManagers.push(newActionManager);
  2160. }
  2161. /**
  2162. * Adds the given texture to this scene.
  2163. * @param newTexture The texture to add
  2164. */
  2165. public addTexture(newTexture: BaseTexture): void {
  2166. if (this._blockEntityCollection) {
  2167. return;
  2168. }
  2169. this.textures.push(newTexture);
  2170. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  2171. }
  2172. /**
  2173. * Switch active camera
  2174. * @param newCamera defines the new active camera
  2175. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  2176. */
  2177. public switchActiveCamera(newCamera: Camera, attachControl = true): void {
  2178. var canvas = this._engine.getInputElement();
  2179. if (!canvas) {
  2180. return;
  2181. }
  2182. if (this.activeCamera) {
  2183. this.activeCamera.detachControl();
  2184. }
  2185. this.activeCamera = newCamera;
  2186. if (attachControl) {
  2187. newCamera.attachControl();
  2188. }
  2189. }
  2190. /**
  2191. * sets the active camera of the scene using its ID
  2192. * @param id defines the camera's ID
  2193. * @return the new active camera or null if none found.
  2194. */
  2195. public setActiveCameraByID(id: string): Nullable<Camera> {
  2196. var camera = this.getCameraByID(id);
  2197. if (camera) {
  2198. this.activeCamera = camera;
  2199. return camera;
  2200. }
  2201. return null;
  2202. }
  2203. /**
  2204. * sets the active camera of the scene using its name
  2205. * @param name defines the camera's name
  2206. * @returns the new active camera or null if none found.
  2207. */
  2208. public setActiveCameraByName(name: string): Nullable<Camera> {
  2209. var camera = this.getCameraByName(name);
  2210. if (camera) {
  2211. this.activeCamera = camera;
  2212. return camera;
  2213. }
  2214. return null;
  2215. }
  2216. /**
  2217. * get an animation group using its name
  2218. * @param name defines the material's name
  2219. * @return the animation group or null if none found.
  2220. */
  2221. public getAnimationGroupByName(name: string): Nullable<AnimationGroup> {
  2222. for (var index = 0; index < this.animationGroups.length; index++) {
  2223. if (this.animationGroups[index].name === name) {
  2224. return this.animationGroups[index];
  2225. }
  2226. }
  2227. return null;
  2228. }
  2229. /**
  2230. * Get a material using its unique id
  2231. * @param uniqueId defines the material's unique id
  2232. * @return the material or null if none found.
  2233. */
  2234. public getMaterialByUniqueID(uniqueId: number): Nullable<Material> {
  2235. for (var index = 0; index < this.materials.length; index++) {
  2236. if (this.materials[index].uniqueId === uniqueId) {
  2237. return this.materials[index];
  2238. }
  2239. }
  2240. return null;
  2241. }
  2242. /**
  2243. * get a material using its id
  2244. * @param id defines the material's ID
  2245. * @return the material or null if none found.
  2246. */
  2247. public getMaterialByID(id: string): Nullable<Material> {
  2248. for (var index = 0; index < this.materials.length; index++) {
  2249. if (this.materials[index].id === id) {
  2250. return this.materials[index];
  2251. }
  2252. }
  2253. return null;
  2254. }
  2255. /**
  2256. * Gets a the last added material using a given id
  2257. * @param id defines the material's ID
  2258. * @return the last material with the given id or null if none found.
  2259. */
  2260. public getLastMaterialByID(id: string): Nullable<Material> {
  2261. for (var index = this.materials.length - 1; index >= 0; index--) {
  2262. if (this.materials[index].id === id) {
  2263. return this.materials[index];
  2264. }
  2265. }
  2266. return null;
  2267. }
  2268. /**
  2269. * Gets a material using its name
  2270. * @param name defines the material's name
  2271. * @return the material or null if none found.
  2272. */
  2273. public getMaterialByName(name: string): Nullable<Material> {
  2274. for (var index = 0; index < this.materials.length; index++) {
  2275. if (this.materials[index].name === name) {
  2276. return this.materials[index];
  2277. }
  2278. }
  2279. return null;
  2280. }
  2281. /**
  2282. * Get a texture using its unique id
  2283. * @param uniqueId defines the texture's unique id
  2284. * @return the texture or null if none found.
  2285. */
  2286. public getTextureByUniqueID(uniqueId: number): Nullable<BaseTexture> {
  2287. for (var index = 0; index < this.textures.length; index++) {
  2288. if (this.textures[index].uniqueId === uniqueId) {
  2289. return this.textures[index];
  2290. }
  2291. }
  2292. return null;
  2293. }
  2294. /**
  2295. * Gets a camera using its id
  2296. * @param id defines the id to look for
  2297. * @returns the camera or null if not found
  2298. */
  2299. public getCameraByID(id: string): Nullable<Camera> {
  2300. for (var index = 0; index < this.cameras.length; index++) {
  2301. if (this.cameras[index].id === id) {
  2302. return this.cameras[index];
  2303. }
  2304. }
  2305. return null;
  2306. }
  2307. /**
  2308. * Gets a camera using its unique id
  2309. * @param uniqueId defines the unique id to look for
  2310. * @returns the camera or null if not found
  2311. */
  2312. public getCameraByUniqueID(uniqueId: number): Nullable<Camera> {
  2313. for (var index = 0; index < this.cameras.length; index++) {
  2314. if (this.cameras[index].uniqueId === uniqueId) {
  2315. return this.cameras[index];
  2316. }
  2317. }
  2318. return null;
  2319. }
  2320. /**
  2321. * Gets a camera using its name
  2322. * @param name defines the camera's name
  2323. * @return the camera or null if none found.
  2324. */
  2325. public getCameraByName(name: string): Nullable<Camera> {
  2326. for (var index = 0; index < this.cameras.length; index++) {
  2327. if (this.cameras[index].name === name) {
  2328. return this.cameras[index];
  2329. }
  2330. }
  2331. return null;
  2332. }
  2333. /**
  2334. * Gets a bone using its id
  2335. * @param id defines the bone's id
  2336. * @return the bone or null if not found
  2337. */
  2338. public getBoneByID(id: string): Nullable<Bone> {
  2339. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2340. var skeleton = this.skeletons[skeletonIndex];
  2341. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2342. if (skeleton.bones[boneIndex].id === id) {
  2343. return skeleton.bones[boneIndex];
  2344. }
  2345. }
  2346. }
  2347. return null;
  2348. }
  2349. /**
  2350. * Gets a bone using its id
  2351. * @param name defines the bone's name
  2352. * @return the bone or null if not found
  2353. */
  2354. public getBoneByName(name: string): Nullable<Bone> {
  2355. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  2356. var skeleton = this.skeletons[skeletonIndex];
  2357. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  2358. if (skeleton.bones[boneIndex].name === name) {
  2359. return skeleton.bones[boneIndex];
  2360. }
  2361. }
  2362. }
  2363. return null;
  2364. }
  2365. /**
  2366. * Gets a light node using its name
  2367. * @param name defines the the light's name
  2368. * @return the light or null if none found.
  2369. */
  2370. public getLightByName(name: string): Nullable<Light> {
  2371. for (var index = 0; index < this.lights.length; index++) {
  2372. if (this.lights[index].name === name) {
  2373. return this.lights[index];
  2374. }
  2375. }
  2376. return null;
  2377. }
  2378. /**
  2379. * Gets a light node using its id
  2380. * @param id defines the light's id
  2381. * @return the light or null if none found.
  2382. */
  2383. public getLightByID(id: string): Nullable<Light> {
  2384. for (var index = 0; index < this.lights.length; index++) {
  2385. if (this.lights[index].id === id) {
  2386. return this.lights[index];
  2387. }
  2388. }
  2389. return null;
  2390. }
  2391. /**
  2392. * Gets a light node using its scene-generated unique ID
  2393. * @param uniqueId defines the light's unique id
  2394. * @return the light or null if none found.
  2395. */
  2396. public getLightByUniqueID(uniqueId: number): Nullable<Light> {
  2397. for (var index = 0; index < this.lights.length; index++) {
  2398. if (this.lights[index].uniqueId === uniqueId) {
  2399. return this.lights[index];
  2400. }
  2401. }
  2402. return null;
  2403. }
  2404. /**
  2405. * Gets a particle system by id
  2406. * @param id defines the particle system id
  2407. * @return the corresponding system or null if none found
  2408. */
  2409. public getParticleSystemByID(id: string): Nullable<IParticleSystem> {
  2410. for (var index = 0; index < this.particleSystems.length; index++) {
  2411. if (this.particleSystems[index].id === id) {
  2412. return this.particleSystems[index];
  2413. }
  2414. }
  2415. return null;
  2416. }
  2417. /**
  2418. * Gets a geometry using its ID
  2419. * @param id defines the geometry's id
  2420. * @return the geometry or null if none found.
  2421. */
  2422. public getGeometryByID(id: string): Nullable<Geometry> {
  2423. for (var index = 0; index < this.geometries.length; index++) {
  2424. if (this.geometries[index].id === id) {
  2425. return this.geometries[index];
  2426. }
  2427. }
  2428. return null;
  2429. }
  2430. private _getGeometryByUniqueID(uniqueId: number): Nullable<Geometry> {
  2431. if (this.geometriesByUniqueId) {
  2432. const index = this.geometriesByUniqueId[uniqueId];
  2433. if (index !== undefined) {
  2434. return this.geometries[index];
  2435. }
  2436. }
  2437. else {
  2438. for (var index = 0; index < this.geometries.length; index++) {
  2439. if (this.geometries[index].uniqueId === uniqueId) {
  2440. return this.geometries[index];
  2441. }
  2442. }
  2443. }
  2444. return null;
  2445. }
  2446. /**
  2447. * Add a new geometry to this scene
  2448. * @param geometry defines the geometry to be added to the scene.
  2449. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  2450. * @return a boolean defining if the geometry was added or not
  2451. */
  2452. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  2453. if (!force && this._getGeometryByUniqueID(geometry.uniqueId)) {
  2454. return false;
  2455. }
  2456. this.addGeometry(geometry);
  2457. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  2458. return true;
  2459. }
  2460. /**
  2461. * Removes an existing geometry
  2462. * @param geometry defines the geometry to be removed from the scene
  2463. * @return a boolean defining if the geometry was removed or not
  2464. */
  2465. public removeGeometry(geometry: Geometry): boolean {
  2466. let index;
  2467. if (this.geometriesByUniqueId) {
  2468. index = this.geometriesByUniqueId[geometry.uniqueId];
  2469. if (index === undefined) {
  2470. return false;
  2471. }
  2472. }
  2473. else {
  2474. index = this.geometries.indexOf(geometry);
  2475. if (index < 0) {
  2476. return false;
  2477. }
  2478. }
  2479. if (index !== this.geometries.length - 1) {
  2480. const lastGeometry = this.geometries[this.geometries.length - 1];
  2481. if (lastGeometry) {
  2482. this.geometries[index] = lastGeometry;
  2483. if (this.geometriesByUniqueId) {
  2484. this.geometriesByUniqueId[lastGeometry.uniqueId] = index;
  2485. this.geometriesByUniqueId[geometry.uniqueId] = undefined;
  2486. }
  2487. }
  2488. }
  2489. this.geometries.pop();
  2490. this.onGeometryRemovedObservable.notifyObservers(geometry);
  2491. return true;
  2492. }
  2493. /**
  2494. * Gets the list of geometries attached to the scene
  2495. * @returns an array of Geometry
  2496. */
  2497. public getGeometries(): Geometry[] {
  2498. return this.geometries;
  2499. }
  2500. /**
  2501. * Gets the first added mesh found of a given ID
  2502. * @param id defines the id to search for
  2503. * @return the mesh found or null if not found at all
  2504. */
  2505. public getMeshByID(id: string): Nullable<AbstractMesh> {
  2506. for (var index = 0; index < this.meshes.length; index++) {
  2507. if (this.meshes[index].id === id) {
  2508. return this.meshes[index];
  2509. }
  2510. }
  2511. return null;
  2512. }
  2513. /**
  2514. * Gets a list of meshes using their id
  2515. * @param id defines the id to search for
  2516. * @returns a list of meshes
  2517. */
  2518. public getMeshesByID(id: string): Array<AbstractMesh> {
  2519. return this.meshes.filter(function(m) {
  2520. return m.id === id;
  2521. });
  2522. }
  2523. /**
  2524. * Gets the first added transform node found of a given ID
  2525. * @param id defines the id to search for
  2526. * @return the found transform node or null if not found at all.
  2527. */
  2528. public getTransformNodeByID(id: string): Nullable<TransformNode> {
  2529. for (var index = 0; index < this.transformNodes.length; index++) {
  2530. if (this.transformNodes[index].id === id) {
  2531. return this.transformNodes[index];
  2532. }
  2533. }
  2534. return null;
  2535. }
  2536. /**
  2537. * Gets a transform node with its auto-generated unique id
  2538. * @param uniqueId efines the unique id to search for
  2539. * @return the found transform node or null if not found at all.
  2540. */
  2541. public getTransformNodeByUniqueID(uniqueId: number): Nullable<TransformNode> {
  2542. for (var index = 0; index < this.transformNodes.length; index++) {
  2543. if (this.transformNodes[index].uniqueId === uniqueId) {
  2544. return this.transformNodes[index];
  2545. }
  2546. }
  2547. return null;
  2548. }
  2549. /**
  2550. * Gets a list of transform nodes using their id
  2551. * @param id defines the id to search for
  2552. * @returns a list of transform nodes
  2553. */
  2554. public getTransformNodesByID(id: string): Array<TransformNode> {
  2555. return this.transformNodes.filter(function(m) {
  2556. return m.id === id;
  2557. });
  2558. }
  2559. /**
  2560. * Gets a mesh with its auto-generated unique id
  2561. * @param uniqueId defines the unique id to search for
  2562. * @return the found mesh or null if not found at all.
  2563. */
  2564. public getMeshByUniqueID(uniqueId: number): Nullable<AbstractMesh> {
  2565. for (var index = 0; index < this.meshes.length; index++) {
  2566. if (this.meshes[index].uniqueId === uniqueId) {
  2567. return this.meshes[index];
  2568. }
  2569. }
  2570. return null;
  2571. }
  2572. /**
  2573. * Gets a the last added mesh using a given id
  2574. * @param id defines the id to search for
  2575. * @return the found mesh or null if not found at all.
  2576. */
  2577. public getLastMeshByID(id: string): Nullable<AbstractMesh> {
  2578. for (var index = this.meshes.length - 1; index >= 0; index--) {
  2579. if (this.meshes[index].id === id) {
  2580. return this.meshes[index];
  2581. }
  2582. }
  2583. return null;
  2584. }
  2585. /**
  2586. * Gets a the last added node (Mesh, Camera, Light) using a given id
  2587. * @param id defines the id to search for
  2588. * @return the found node or null if not found at all
  2589. */
  2590. public getLastEntryByID(id: string): Nullable<Node> {
  2591. var index: number;
  2592. for (index = this.meshes.length - 1; index >= 0; index--) {
  2593. if (this.meshes[index].id === id) {
  2594. return this.meshes[index];
  2595. }
  2596. }
  2597. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  2598. if (this.transformNodes[index].id === id) {
  2599. return this.transformNodes[index];
  2600. }
  2601. }
  2602. for (index = this.cameras.length - 1; index >= 0; index--) {
  2603. if (this.cameras[index].id === id) {
  2604. return this.cameras[index];
  2605. }
  2606. }
  2607. for (index = this.lights.length - 1; index >= 0; index--) {
  2608. if (this.lights[index].id === id) {
  2609. return this.lights[index];
  2610. }
  2611. }
  2612. return null;
  2613. }
  2614. /**
  2615. * Gets a node (Mesh, Camera, Light) using a given id
  2616. * @param id defines the id to search for
  2617. * @return the found node or null if not found at all
  2618. */
  2619. public getNodeByID(id: string): Nullable<Node> {
  2620. const mesh = this.getMeshByID(id);
  2621. if (mesh) {
  2622. return mesh;
  2623. }
  2624. const transformNode = this.getTransformNodeByID(id);
  2625. if (transformNode) {
  2626. return transformNode;
  2627. }
  2628. const light = this.getLightByID(id);
  2629. if (light) {
  2630. return light;
  2631. }
  2632. const camera = this.getCameraByID(id);
  2633. if (camera) {
  2634. return camera;
  2635. }
  2636. const bone = this.getBoneByID(id);
  2637. if (bone) {
  2638. return bone;
  2639. }
  2640. return null;
  2641. }
  2642. /**
  2643. * Gets a node (Mesh, Camera, Light) using a given name
  2644. * @param name defines the name to search for
  2645. * @return the found node or null if not found at all.
  2646. */
  2647. public getNodeByName(name: string): Nullable<Node> {
  2648. const mesh = this.getMeshByName(name);
  2649. if (mesh) {
  2650. return mesh;
  2651. }
  2652. const transformNode = this.getTransformNodeByName(name);
  2653. if (transformNode) {
  2654. return transformNode;
  2655. }
  2656. const light = this.getLightByName(name);
  2657. if (light) {
  2658. return light;
  2659. }
  2660. const camera = this.getCameraByName(name);
  2661. if (camera) {
  2662. return camera;
  2663. }
  2664. const bone = this.getBoneByName(name);
  2665. if (bone) {
  2666. return bone;
  2667. }
  2668. return null;
  2669. }
  2670. /**
  2671. * Gets a mesh using a given name
  2672. * @param name defines the name to search for
  2673. * @return the found mesh or null if not found at all.
  2674. */
  2675. public getMeshByName(name: string): Nullable<AbstractMesh> {
  2676. for (var index = 0; index < this.meshes.length; index++) {
  2677. if (this.meshes[index].name === name) {
  2678. return this.meshes[index];
  2679. }
  2680. }
  2681. return null;
  2682. }
  2683. /**
  2684. * Gets a transform node using a given name
  2685. * @param name defines the name to search for
  2686. * @return the found transform node or null if not found at all.
  2687. */
  2688. public getTransformNodeByName(name: string): Nullable<TransformNode> {
  2689. for (var index = 0; index < this.transformNodes.length; index++) {
  2690. if (this.transformNodes[index].name === name) {
  2691. return this.transformNodes[index];
  2692. }
  2693. }
  2694. return null;
  2695. }
  2696. /**
  2697. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  2698. * @param id defines the id to search for
  2699. * @return the found skeleton or null if not found at all.
  2700. */
  2701. public getLastSkeletonByID(id: string): Nullable<Skeleton> {
  2702. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  2703. if (this.skeletons[index].id === id) {
  2704. return this.skeletons[index];
  2705. }
  2706. }
  2707. return null;
  2708. }
  2709. /**
  2710. * Gets a skeleton using a given auto generated unique id
  2711. * @param uniqueId defines the unique id to search for
  2712. * @return the found skeleton or null if not found at all.
  2713. */
  2714. public getSkeletonByUniqueId(uniqueId: number): Nullable<Skeleton> {
  2715. for (var index = 0; index < this.skeletons.length; index++) {
  2716. if (this.skeletons[index].uniqueId === uniqueId) {
  2717. return this.skeletons[index];
  2718. }
  2719. }
  2720. return null;
  2721. }
  2722. /**
  2723. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  2724. * @param id defines the id to search for
  2725. * @return the found skeleton or null if not found at all.
  2726. */
  2727. public getSkeletonById(id: string): Nullable<Skeleton> {
  2728. for (var index = 0; index < this.skeletons.length; index++) {
  2729. if (this.skeletons[index].id === id) {
  2730. return this.skeletons[index];
  2731. }
  2732. }
  2733. return null;
  2734. }
  2735. /**
  2736. * Gets a skeleton using a given name
  2737. * @param name defines the name to search for
  2738. * @return the found skeleton or null if not found at all.
  2739. */
  2740. public getSkeletonByName(name: string): Nullable<Skeleton> {
  2741. for (var index = 0; index < this.skeletons.length; index++) {
  2742. if (this.skeletons[index].name === name) {
  2743. return this.skeletons[index];
  2744. }
  2745. }
  2746. return null;
  2747. }
  2748. /**
  2749. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  2750. * @param id defines the id to search for
  2751. * @return the found morph target manager or null if not found at all.
  2752. */
  2753. public getMorphTargetManagerById(id: number): Nullable<MorphTargetManager> {
  2754. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  2755. if (this.morphTargetManagers[index].uniqueId === id) {
  2756. return this.morphTargetManagers[index];
  2757. }
  2758. }
  2759. return null;
  2760. }
  2761. /**
  2762. * Gets a morph target using a given id (if many are found, this function will pick the first one)
  2763. * @param id defines the id to search for
  2764. * @return the found morph target or null if not found at all.
  2765. */
  2766. public getMorphTargetById(id: string): Nullable<MorphTarget> {
  2767. for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) {
  2768. const morphTargetManager = this.morphTargetManagers[managerIndex];
  2769. for (let index = 0; index < morphTargetManager.numTargets; ++index) {
  2770. const target = morphTargetManager.getTarget(index);
  2771. if (target.id === id) {
  2772. return target;
  2773. }
  2774. }
  2775. }
  2776. return null;
  2777. }
  2778. /**
  2779. * Gets a morph target using a given name (if many are found, this function will pick the first one)
  2780. * @param name defines the name to search for
  2781. * @return the found morph target or null if not found at all.
  2782. */
  2783. public getMorphTargetByName(name: string): Nullable<MorphTarget> {
  2784. for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) {
  2785. const morphTargetManager = this.morphTargetManagers[managerIndex];
  2786. for (let index = 0; index < morphTargetManager.numTargets; ++index) {
  2787. const target = morphTargetManager.getTarget(index);
  2788. if (target.name === name) {
  2789. return target;
  2790. }
  2791. }
  2792. }
  2793. return null;
  2794. }
  2795. /**
  2796. * Gets a post process using a given name (if many are found, this function will pick the first one)
  2797. * @param name defines the name to search for
  2798. * @return the found post process or null if not found at all.
  2799. */
  2800. public getPostProcessByName(name: string): Nullable<PostProcess> {
  2801. for (let postProcessIndex = 0; postProcessIndex < this.postProcesses.length; ++postProcessIndex) {
  2802. const postProcess = this.postProcesses[postProcessIndex];
  2803. if (postProcess.name === name) {
  2804. return postProcess;
  2805. }
  2806. }
  2807. return null;
  2808. }
  2809. /**
  2810. * Gets a boolean indicating if the given mesh is active
  2811. * @param mesh defines the mesh to look for
  2812. * @returns true if the mesh is in the active list
  2813. */
  2814. public isActiveMesh(mesh: AbstractMesh): boolean {
  2815. return (this._activeMeshes.indexOf(mesh) !== -1);
  2816. }
  2817. /**
  2818. * Return a unique id as a string which can serve as an identifier for the scene
  2819. */
  2820. public get uid(): string {
  2821. if (!this._uid) {
  2822. this._uid = Tools.RandomId();
  2823. }
  2824. return this._uid;
  2825. }
  2826. /**
  2827. * Add an externaly attached data from its key.
  2828. * This method call will fail and return false, if such key already exists.
  2829. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2830. * @param key the unique key that identifies the data
  2831. * @param data the data object to associate to the key for this Engine instance
  2832. * @return true if no such key were already present and the data was added successfully, false otherwise
  2833. */
  2834. public addExternalData<T>(key: string, data: T): boolean {
  2835. if (!this._externalData) {
  2836. this._externalData = new StringDictionary<Object>();
  2837. }
  2838. return this._externalData.add(key, data);
  2839. }
  2840. /**
  2841. * Get an externaly attached data from its key
  2842. * @param key the unique key that identifies the data
  2843. * @return the associated data, if present (can be null), or undefined if not present
  2844. */
  2845. public getExternalData<T>(key: string): Nullable<T> {
  2846. if (!this._externalData) {
  2847. return null;
  2848. }
  2849. return <T>this._externalData.get(key);
  2850. }
  2851. /**
  2852. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2853. * @param key the unique key that identifies the data
  2854. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2855. * @return the associated data, can be null if the factory returned null.
  2856. */
  2857. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  2858. if (!this._externalData) {
  2859. this._externalData = new StringDictionary<Object>();
  2860. }
  2861. return <T>this._externalData.getOrAddWithFactory(key, factory);
  2862. }
  2863. /**
  2864. * Remove an externaly attached data from the Engine instance
  2865. * @param key the unique key that identifies the data
  2866. * @return true if the data was successfully removed, false if it doesn't exist
  2867. */
  2868. public removeExternalData(key: string): boolean {
  2869. return this._externalData.remove(key);
  2870. }
  2871. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh, initialMesh: AbstractMesh): void {
  2872. if (initialMesh.hasInstances || initialMesh.isAnInstance || this.dispatchAllSubMeshesOfActiveMeshes || this._skipFrustumClipping || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  2873. for (let step of this._evaluateSubMeshStage) {
  2874. step.action(mesh, subMesh);
  2875. }
  2876. const material = subMesh.getMaterial();
  2877. if (material !== null && material !== undefined) {
  2878. // Render targets
  2879. if (material.hasRenderTargetTextures && material.getRenderTargetTextures != null) {
  2880. if (this._processedMaterials.indexOf(material) === -1) {
  2881. this._processedMaterials.push(material);
  2882. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures!());
  2883. }
  2884. }
  2885. // Dispatch
  2886. this._renderingManager.dispatch(subMesh, mesh, material);
  2887. }
  2888. }
  2889. }
  2890. /**
  2891. * Clear the processed materials smart array preventing retention point in material dispose.
  2892. */
  2893. public freeProcessedMaterials(): void {
  2894. this._processedMaterials.dispose();
  2895. }
  2896. private _preventFreeActiveMeshesAndRenderingGroups = false;
  2897. /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
  2898. * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
  2899. * when disposing several meshes in a row or a hierarchy of meshes.
  2900. * When used, it is the responsability of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
  2901. */
  2902. public get blockfreeActiveMeshesAndRenderingGroups(): boolean {
  2903. return this._preventFreeActiveMeshesAndRenderingGroups;
  2904. }
  2905. public set blockfreeActiveMeshesAndRenderingGroups(value: boolean) {
  2906. if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
  2907. return;
  2908. }
  2909. if (value) {
  2910. this.freeActiveMeshes();
  2911. this.freeRenderingGroups();
  2912. }
  2913. this._preventFreeActiveMeshesAndRenderingGroups = value;
  2914. }
  2915. /**
  2916. * Clear the active meshes smart array preventing retention point in mesh dispose.
  2917. */
  2918. public freeActiveMeshes(): void {
  2919. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  2920. return;
  2921. }
  2922. this._activeMeshes.dispose();
  2923. if (this.activeCamera && this.activeCamera._activeMeshes) {
  2924. this.activeCamera._activeMeshes.dispose();
  2925. }
  2926. if (this.activeCameras) {
  2927. for (let i = 0; i < this.activeCameras.length; i++) {
  2928. let activeCamera = this.activeCameras[i];
  2929. if (activeCamera && activeCamera._activeMeshes) {
  2930. activeCamera._activeMeshes.dispose();
  2931. }
  2932. }
  2933. }
  2934. }
  2935. /**
  2936. * Clear the info related to rendering groups preventing retention points during dispose.
  2937. */
  2938. public freeRenderingGroups(): void {
  2939. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  2940. return;
  2941. }
  2942. if (this._renderingManager) {
  2943. this._renderingManager.freeRenderingGroups();
  2944. }
  2945. if (this.textures) {
  2946. for (let i = 0; i < this.textures.length; i++) {
  2947. let texture = this.textures[i];
  2948. if (texture && (<RenderTargetTexture>texture).renderList) {
  2949. (<RenderTargetTexture>texture).freeRenderingGroups();
  2950. }
  2951. }
  2952. }
  2953. }
  2954. /** @hidden */
  2955. public _isInIntermediateRendering(): boolean {
  2956. return this._intermediateRendering;
  2957. }
  2958. /**
  2959. * Lambda returning the list of potentially active meshes.
  2960. */
  2961. public getActiveMeshCandidates: () => ISmartArrayLike<AbstractMesh>;
  2962. /**
  2963. * Lambda returning the list of potentially active sub meshes.
  2964. */
  2965. public getActiveSubMeshCandidates: (mesh: AbstractMesh) => ISmartArrayLike<SubMesh>;
  2966. /**
  2967. * Lambda returning the list of potentially intersecting sub meshes.
  2968. */
  2969. public getIntersectingSubMeshCandidates: (mesh: AbstractMesh, localRay: Ray) => ISmartArrayLike<SubMesh>;
  2970. /**
  2971. * Lambda returning the list of potentially colliding sub meshes.
  2972. */
  2973. public getCollidingSubMeshCandidates: (mesh: AbstractMesh, collider: Collider) => ISmartArrayLike<SubMesh>;
  2974. private _activeMeshesFrozen = false;
  2975. private _skipEvaluateActiveMeshesCompletely = false;
  2976. /**
  2977. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  2978. * @param skipEvaluateActiveMeshes defines an optional boolean indicating that the evaluate active meshes step must be completely skipped
  2979. * @param onSuccess optional success callback
  2980. * @param onError optional error callback
  2981. * @returns the current scene
  2982. */
  2983. public freezeActiveMeshes(skipEvaluateActiveMeshes = false, onSuccess?: () => void, onError?: (message: string) => void): Scene {
  2984. this.executeWhenReady(() => {
  2985. if (!this.activeCamera) {
  2986. onError && onError('No active camera found');
  2987. return;
  2988. }
  2989. if (!this._frustumPlanes) {
  2990. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  2991. }
  2992. this._evaluateActiveMeshes();
  2993. this._activeMeshesFrozen = true;
  2994. this._skipEvaluateActiveMeshesCompletely = skipEvaluateActiveMeshes;
  2995. for (var index = 0; index < this._activeMeshes.length; index++) {
  2996. this._activeMeshes.data[index]._freeze();
  2997. }
  2998. onSuccess && onSuccess();
  2999. });
  3000. return this;
  3001. }
  3002. /**
  3003. * Use this function to restart evaluating active meshes on every frame
  3004. * @returns the current scene
  3005. */
  3006. public unfreezeActiveMeshes(): Scene {
  3007. for (var index = 0; index < this.meshes.length; index++) {
  3008. const mesh = this.meshes[index];
  3009. if (mesh._internalAbstractMeshDataInfo) {
  3010. mesh._internalAbstractMeshDataInfo._isActive = false;
  3011. }
  3012. }
  3013. for (var index = 0; index < this._activeMeshes.length; index++) {
  3014. this._activeMeshes.data[index]._unFreeze();
  3015. }
  3016. this._activeMeshesFrozen = false;
  3017. return this;
  3018. }
  3019. private _evaluateActiveMeshes(): void {
  3020. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  3021. if (!this._skipEvaluateActiveMeshesCompletely) {
  3022. const len = this._activeMeshes.length;
  3023. for (let i = 0; i < len; i++) {
  3024. let mesh = this._activeMeshes.data[i];
  3025. mesh.computeWorldMatrix();
  3026. }
  3027. }
  3028. if (this._activeParticleSystems) {
  3029. const psLength = this._activeParticleSystems.length;
  3030. for (let i = 0; i < psLength; i++) {
  3031. this._activeParticleSystems.data[i].animate();
  3032. }
  3033. }
  3034. return;
  3035. }
  3036. if (!this.activeCamera) {
  3037. return;
  3038. }
  3039. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  3040. this.activeCamera._activeMeshes.reset();
  3041. this._activeMeshes.reset();
  3042. this._renderingManager.reset();
  3043. this._processedMaterials.reset();
  3044. this._activeParticleSystems.reset();
  3045. this._activeSkeletons.reset();
  3046. this._softwareSkinnedMeshes.reset();
  3047. for (let step of this._beforeEvaluateActiveMeshStage) {
  3048. step.action();
  3049. }
  3050. // Determine mesh candidates
  3051. const meshes = this.getActiveMeshCandidates();
  3052. // Check each mesh
  3053. const len = meshes.length;
  3054. for (let i = 0; i < len; i++) {
  3055. const mesh = meshes.data[i];
  3056. if (mesh.isBlocked) {
  3057. continue;
  3058. }
  3059. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  3060. if (!mesh.isReady() || !mesh.isEnabled() || mesh.scaling.lengthSquared() === 0) {
  3061. continue;
  3062. }
  3063. mesh.computeWorldMatrix();
  3064. // Intersections
  3065. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(Constants.ACTION_OnIntersectionEnterTrigger, Constants.ACTION_OnIntersectionExitTrigger)) {
  3066. this._meshesForIntersections.pushNoDuplicate(mesh);
  3067. }
  3068. // Switch to current LOD
  3069. let meshToRender = this.customLODSelector ? this.customLODSelector(mesh, this.activeCamera) : mesh.getLOD(this.activeCamera);
  3070. if (meshToRender === undefined || meshToRender === null) {
  3071. continue;
  3072. }
  3073. mesh._internalAbstractMeshDataInfo._currentLOD = meshToRender;
  3074. // Compute world matrix if LOD is billboard
  3075. if (meshToRender !== mesh && meshToRender.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  3076. meshToRender.computeWorldMatrix();
  3077. }
  3078. mesh._preActivate();
  3079. if (mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && (this._skipFrustumClipping || mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
  3080. this._activeMeshes.push(mesh);
  3081. this.activeCamera._activeMeshes.push(mesh);
  3082. if (meshToRender !== mesh) {
  3083. meshToRender._activate(this._renderId, false);
  3084. }
  3085. for (let step of this._preActiveMeshStage) {
  3086. step.action(mesh);
  3087. }
  3088. if (mesh._activate(this._renderId, false)) {
  3089. if (!mesh.isAnInstance) {
  3090. meshToRender._internalAbstractMeshDataInfo._onlyForInstances = false;
  3091. } else {
  3092. if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) {
  3093. meshToRender = mesh;
  3094. }
  3095. }
  3096. meshToRender._internalAbstractMeshDataInfo._isActive = true;
  3097. this._activeMesh(mesh, meshToRender);
  3098. }
  3099. mesh._postActivate();
  3100. }
  3101. }
  3102. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  3103. // Particle systems
  3104. if (this.particlesEnabled) {
  3105. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  3106. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  3107. var particleSystem = this.particleSystems[particleIndex];
  3108. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  3109. continue;
  3110. }
  3111. let emitter = <any>particleSystem.emitter;
  3112. if (!emitter.position || emitter.isEnabled()) {
  3113. this._activeParticleSystems.push(particleSystem);
  3114. particleSystem.animate();
  3115. this._renderingManager.dispatchParticles(particleSystem);
  3116. }
  3117. }
  3118. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  3119. }
  3120. }
  3121. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  3122. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  3123. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  3124. mesh.skeleton.prepare();
  3125. }
  3126. if (!mesh.computeBonesUsingShaders) {
  3127. this._softwareSkinnedMeshes.pushNoDuplicate(<Mesh>mesh);
  3128. }
  3129. }
  3130. if (
  3131. mesh !== undefined && mesh !== null
  3132. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0
  3133. ) {
  3134. const subMeshes = this.getActiveSubMeshCandidates(mesh);
  3135. const len = subMeshes.length;
  3136. for (let i = 0; i < len; i++) {
  3137. const subMesh = subMeshes.data[i];
  3138. this._evaluateSubMesh(subMesh, mesh, sourceMesh);
  3139. }
  3140. }
  3141. }
  3142. /**
  3143. * Update the transform matrix to update from the current active camera
  3144. * @param force defines a boolean used to force the update even if cache is up to date
  3145. */
  3146. public updateTransformMatrix(force?: boolean): void {
  3147. if (!this.activeCamera) {
  3148. return;
  3149. }
  3150. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  3151. }
  3152. private _bindFrameBuffer() {
  3153. if (this.activeCamera && this.activeCamera._multiviewTexture) {
  3154. this.activeCamera._multiviewTexture._bindFrameBuffer();
  3155. } else if (this.activeCamera && this.activeCamera.outputRenderTarget) {
  3156. var useMultiview = this.getEngine().getCaps().multiview && this.activeCamera.outputRenderTarget && this.activeCamera.outputRenderTarget.getViewCount() > 1;
  3157. if (useMultiview) {
  3158. this.activeCamera.outputRenderTarget._bindFrameBuffer();
  3159. } else {
  3160. var internalTexture = this.activeCamera.outputRenderTarget.getInternalTexture();
  3161. if (internalTexture) {
  3162. this.getEngine().bindFramebuffer(internalTexture);
  3163. } else {
  3164. Logger.Error("Camera contains invalid customDefaultRenderTarget");
  3165. }
  3166. }
  3167. } else {
  3168. this.getEngine().restoreDefaultFramebuffer(); // Restore back buffer if needed
  3169. }
  3170. }
  3171. /** @hidden */
  3172. public _allowPostProcessClearColor = true;
  3173. /** @hidden */
  3174. public _renderForCamera(camera: Camera, rigParent?: Camera): void {
  3175. if (camera && camera._skipRendering) {
  3176. return;
  3177. }
  3178. var engine = this._engine;
  3179. // Use _activeCamera instead of activeCamera to avoid onActiveCameraChanged
  3180. this._activeCamera = camera;
  3181. if (!this.activeCamera) {
  3182. throw new Error("Active camera not set");
  3183. }
  3184. // Viewport
  3185. engine.setViewport(this.activeCamera.viewport);
  3186. // Camera
  3187. this.resetCachedMaterial();
  3188. this._renderId++;
  3189. var useMultiview = this.getEngine().getCaps().multiview && camera.outputRenderTarget && camera.outputRenderTarget.getViewCount() > 1;
  3190. if (useMultiview) {
  3191. this.setTransformMatrix(camera._rigCameras[0].getViewMatrix(), camera._rigCameras[0].getProjectionMatrix(), camera._rigCameras[1].getViewMatrix(), camera._rigCameras[1].getProjectionMatrix());
  3192. } else {
  3193. this.updateTransformMatrix();
  3194. }
  3195. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  3196. // Meshes
  3197. this._evaluateActiveMeshes();
  3198. // Software skinning
  3199. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  3200. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  3201. mesh.applySkeleton(<Skeleton>mesh.skeleton);
  3202. }
  3203. // Render targets
  3204. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3205. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  3206. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  3207. }
  3208. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  3209. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  3210. }
  3211. // Collects render targets from external components.
  3212. for (let step of this._gatherActiveCameraRenderTargetsStage) {
  3213. step.action(this._renderTargets);
  3214. }
  3215. let needRebind = false;
  3216. if (this.renderTargetsEnabled) {
  3217. this._intermediateRendering = true;
  3218. if (this._renderTargets.length > 0) {
  3219. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3220. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  3221. let renderTarget = this._renderTargets.data[renderIndex];
  3222. if (renderTarget._shouldRender()) {
  3223. this._renderId++;
  3224. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  3225. renderTarget.render((<boolean>hasSpecialRenderTargetCamera), this.dumpNextRenderTargets);
  3226. needRebind = true;
  3227. }
  3228. }
  3229. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  3230. this._renderId++;
  3231. }
  3232. for (let step of this._cameraDrawRenderTargetStage) {
  3233. needRebind = step.action(this.activeCamera) || needRebind;
  3234. }
  3235. this._intermediateRendering = false;
  3236. // Need to bind if sub-camera has an outputRenderTarget eg. for webXR
  3237. if (this.activeCamera && this.activeCamera.outputRenderTarget) {
  3238. needRebind = true;
  3239. }
  3240. }
  3241. // Restore framebuffer after rendering to targets
  3242. if (needRebind && !this.prePass) {
  3243. this._bindFrameBuffer();
  3244. }
  3245. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  3246. // Prepare Frame
  3247. if (this.postProcessManager && !camera._multiviewTexture && !this.prePass) {
  3248. this.postProcessManager._prepareFrame();
  3249. }
  3250. // Before Camera Draw
  3251. for (let step of this._beforeCameraDrawStage) {
  3252. step.action(this.activeCamera);
  3253. }
  3254. // Render
  3255. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  3256. this._renderingManager.render(null, null, true, true);
  3257. this.onAfterDrawPhaseObservable.notifyObservers(this);
  3258. // After Camera Draw
  3259. for (let step of this._afterCameraDrawStage) {
  3260. step.action(this.activeCamera);
  3261. }
  3262. // Finalize frame
  3263. if (this.postProcessManager && !camera._multiviewTexture) {
  3264. // if the camera has an output render target, render the post process to the render target
  3265. const texture = camera.outputRenderTarget ? camera.outputRenderTarget.getInternalTexture()! : undefined;
  3266. this.postProcessManager._finalizeFrame(camera.isIntermediate, texture);
  3267. }
  3268. // Reset some special arrays
  3269. this._renderTargets.reset();
  3270. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  3271. }
  3272. private _processSubCameras(camera: Camera): void {
  3273. if (camera.cameraRigMode === Camera.RIG_MODE_NONE || (camera.outputRenderTarget && camera.outputRenderTarget.getViewCount() > 1 && this.getEngine().getCaps().multiview)) {
  3274. this._renderForCamera(camera);
  3275. this.onAfterRenderCameraObservable.notifyObservers(camera);
  3276. return;
  3277. }
  3278. if (camera._useMultiviewToSingleView) {
  3279. this._renderMultiviewToSingleView(camera);
  3280. } else {
  3281. // rig cameras
  3282. for (var index = 0; index < camera._rigCameras.length; index++) {
  3283. this._renderForCamera(camera._rigCameras[index], camera);
  3284. }
  3285. }
  3286. // Use _activeCamera instead of activeCamera to avoid onActiveCameraChanged
  3287. this._activeCamera = camera;
  3288. this.setTransformMatrix(this._activeCamera.getViewMatrix(), this._activeCamera.getProjectionMatrix());
  3289. this.onAfterRenderCameraObservable.notifyObservers(camera);
  3290. }
  3291. private _checkIntersections(): void {
  3292. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  3293. var sourceMesh = this._meshesForIntersections.data[index];
  3294. if (!sourceMesh.actionManager) {
  3295. continue;
  3296. }
  3297. for (var actionIndex = 0; sourceMesh.actionManager && actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  3298. var action = sourceMesh.actionManager.actions[actionIndex];
  3299. if (action.trigger === Constants.ACTION_OnIntersectionEnterTrigger || action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3300. var parameters = action.getTriggerParameter();
  3301. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  3302. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  3303. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  3304. if (areIntersecting && currentIntersectionInProgress === -1) {
  3305. if (action.trigger === Constants.ACTION_OnIntersectionEnterTrigger) {
  3306. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3307. sourceMesh._intersectionsInProgress.push(otherMesh);
  3308. } else if (action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3309. sourceMesh._intersectionsInProgress.push(otherMesh);
  3310. }
  3311. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  3312. //They intersected, and now they don't.
  3313. //is this trigger an exit trigger? execute an event.
  3314. if (action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3315. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  3316. }
  3317. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  3318. if (!sourceMesh.actionManager.hasSpecificTrigger(Constants.ACTION_OnIntersectionExitTrigger, (parameter) => {
  3319. var parameterMesh = parameter instanceof AbstractMesh ? parameter : parameter.mesh;
  3320. return otherMesh === parameterMesh;
  3321. }) || action.trigger === Constants.ACTION_OnIntersectionExitTrigger) {
  3322. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  3323. }
  3324. }
  3325. }
  3326. }
  3327. }
  3328. }
  3329. /** @hidden */
  3330. public _advancePhysicsEngineStep(step: number) {
  3331. // Do nothing. Code will be replaced if physics engine component is referenced
  3332. }
  3333. /**
  3334. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  3335. */
  3336. public getDeterministicFrameTime: () => number = () => {
  3337. return this._engine.getTimeStep();
  3338. }
  3339. /** @hidden */
  3340. public _animate(): void {
  3341. // Nothing to do as long as Animatable have not been imported.
  3342. }
  3343. /** Execute all animations (for a frame) */
  3344. public animate() {
  3345. if (this._engine.isDeterministicLockStep()) {
  3346. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  3347. let defaultFrameTime = this._engine.getTimeStep();
  3348. var defaultFPS = (1000.0 / defaultFrameTime) / 1000.0;
  3349. let stepsTaken = 0;
  3350. var maxSubSteps = this._engine.getLockstepMaxSteps();
  3351. var internalSteps = Math.floor(deltaTime / defaultFrameTime);
  3352. internalSteps = Math.min(internalSteps, maxSubSteps);
  3353. while (deltaTime > 0 && stepsTaken < internalSteps) {
  3354. this.onBeforeStepObservable.notifyObservers(this);
  3355. // Animations
  3356. this._animationRatio = defaultFrameTime * defaultFPS;
  3357. this._animate();
  3358. this.onAfterAnimationsObservable.notifyObservers(this);
  3359. // Physics
  3360. if (this.physicsEnabled) {
  3361. this._advancePhysicsEngineStep(defaultFrameTime);
  3362. }
  3363. this.onAfterStepObservable.notifyObservers(this);
  3364. this._currentStepId++;
  3365. stepsTaken++;
  3366. deltaTime -= defaultFrameTime;
  3367. }
  3368. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  3369. }
  3370. else {
  3371. // Animations
  3372. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  3373. this._animationRatio = deltaTime * (60.0 / 1000.0);
  3374. this._animate();
  3375. this.onAfterAnimationsObservable.notifyObservers(this);
  3376. // Physics
  3377. if (this.physicsEnabled) {
  3378. this._advancePhysicsEngineStep(deltaTime);
  3379. }
  3380. }
  3381. }
  3382. /**
  3383. * Render the scene
  3384. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  3385. * @param ignoreAnimations defines a boolean indicating if animations should not be executed (false by default)
  3386. */
  3387. public render(updateCameras = true, ignoreAnimations = false): void {
  3388. if (this.isDisposed) {
  3389. return;
  3390. }
  3391. if (this.onReadyObservable.hasObservers() && this._executeWhenReadyTimeoutId === -1) {
  3392. this._checkIsReady();
  3393. }
  3394. this._frameId++;
  3395. // Register components that have been associated lately to the scene.
  3396. this._registerTransientComponents();
  3397. this._activeParticles.fetchNewFrame();
  3398. this._totalVertices.fetchNewFrame();
  3399. this._activeIndices.fetchNewFrame();
  3400. this._activeBones.fetchNewFrame();
  3401. this._meshesForIntersections.reset();
  3402. this.resetCachedMaterial();
  3403. this.onBeforeAnimationsObservable.notifyObservers(this);
  3404. // Actions
  3405. if (this.actionManager) {
  3406. this.actionManager.processTrigger(Constants.ACTION_OnEveryFrameTrigger);
  3407. }
  3408. // Animations
  3409. if (!ignoreAnimations) {
  3410. this.animate();
  3411. }
  3412. // Before camera update steps
  3413. for (let step of this._beforeCameraUpdateStage) {
  3414. step.action();
  3415. }
  3416. // Update Cameras
  3417. if (updateCameras) {
  3418. if (this.activeCameras.length > 0) {
  3419. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  3420. let camera = this.activeCameras[cameraIndex];
  3421. camera.update();
  3422. if (camera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  3423. // rig cameras
  3424. for (var index = 0; index < camera._rigCameras.length; index++) {
  3425. camera._rigCameras[index].update();
  3426. }
  3427. }
  3428. }
  3429. } else if (this.activeCamera) {
  3430. this.activeCamera.update();
  3431. if (this.activeCamera.cameraRigMode !== Camera.RIG_MODE_NONE) {
  3432. // rig cameras
  3433. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  3434. this.activeCamera._rigCameras[index].update();
  3435. }
  3436. }
  3437. }
  3438. }
  3439. // Before render
  3440. this.onBeforeRenderObservable.notifyObservers(this);
  3441. // Customs render targets
  3442. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  3443. var engine = this.getEngine();
  3444. var currentActiveCamera = this.activeCamera;
  3445. if (this.renderTargetsEnabled) {
  3446. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  3447. this._intermediateRendering = true;
  3448. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  3449. var renderTarget = this.customRenderTargets[customIndex];
  3450. if (renderTarget._shouldRender()) {
  3451. this._renderId++;
  3452. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  3453. if (!this.activeCamera) {
  3454. throw new Error("Active camera not set");
  3455. }
  3456. // Viewport
  3457. engine.setViewport(this.activeCamera.viewport);
  3458. // Camera
  3459. this.updateTransformMatrix();
  3460. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  3461. }
  3462. }
  3463. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  3464. this._intermediateRendering = false;
  3465. this._renderId++;
  3466. }
  3467. // Restore back buffer
  3468. this.activeCamera = currentActiveCamera;
  3469. if (this._activeCamera && this._activeCamera.cameraRigMode !== Camera.RIG_MODE_CUSTOM && !this.prePass) {
  3470. this._bindFrameBuffer();
  3471. }
  3472. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  3473. for (let step of this._beforeClearStage) {
  3474. step.action();
  3475. }
  3476. // Clear
  3477. if ((this.autoClearDepthAndStencil || this.autoClear) && !this.prePass) {
  3478. this._engine.clear(this.clearColor,
  3479. this.autoClear || this.forceWireframe || this.forcePointsCloud,
  3480. this.autoClearDepthAndStencil,
  3481. this.autoClearDepthAndStencil);
  3482. }
  3483. // Collects render targets from external components.
  3484. for (let step of this._gatherRenderTargetsStage) {
  3485. step.action(this._renderTargets);
  3486. }
  3487. // Multi-cameras?
  3488. if (this.activeCameras.length > 0) {
  3489. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  3490. if (cameraIndex > 0) {
  3491. this._engine.clear(null, false, true, true);
  3492. }
  3493. this._processSubCameras(this.activeCameras[cameraIndex]);
  3494. }
  3495. } else {
  3496. if (!this.activeCamera) {
  3497. throw new Error("No camera defined");
  3498. }
  3499. this._processSubCameras(this.activeCamera);
  3500. }
  3501. // Intersection checks
  3502. this._checkIntersections();
  3503. // Executes the after render stage actions.
  3504. for (let step of this._afterRenderStage) {
  3505. step.action();
  3506. }
  3507. // After render
  3508. if (this.afterRender) {
  3509. this.afterRender();
  3510. }
  3511. this.onAfterRenderObservable.notifyObservers(this);
  3512. // Cleaning
  3513. if (this._toBeDisposed.length) {
  3514. for (var index = 0; index < this._toBeDisposed.length; index++) {
  3515. var data = this._toBeDisposed[index];
  3516. if (data) {
  3517. data.dispose();
  3518. }
  3519. }
  3520. this._toBeDisposed = [];
  3521. }
  3522. if (this.dumpNextRenderTargets) {
  3523. this.dumpNextRenderTargets = false;
  3524. }
  3525. this._activeBones.addCount(0, true);
  3526. this._activeIndices.addCount(0, true);
  3527. this._activeParticles.addCount(0, true);
  3528. }
  3529. /**
  3530. * Freeze all materials
  3531. * A frozen material will not be updatable but should be faster to render
  3532. */
  3533. public freezeMaterials(): void {
  3534. for (var i = 0; i < this.materials.length; i++) {
  3535. this.materials[i].freeze();
  3536. }
  3537. }
  3538. /**
  3539. * Unfreeze all materials
  3540. * A frozen material will not be updatable but should be faster to render
  3541. */
  3542. public unfreezeMaterials(): void {
  3543. for (var i = 0; i < this.materials.length; i++) {
  3544. this.materials[i].unfreeze();
  3545. }
  3546. }
  3547. /**
  3548. * Releases all held ressources
  3549. */
  3550. public dispose(): void {
  3551. this.beforeRender = null;
  3552. this.afterRender = null;
  3553. if (EngineStore._LastCreatedScene === this) {
  3554. EngineStore._LastCreatedScene = null;
  3555. }
  3556. this.skeletons = [];
  3557. this.morphTargetManagers = [];
  3558. this._transientComponents = [];
  3559. this._isReadyForMeshStage.clear();
  3560. this._beforeEvaluateActiveMeshStage.clear();
  3561. this._evaluateSubMeshStage.clear();
  3562. this._preActiveMeshStage.clear();
  3563. this._cameraDrawRenderTargetStage.clear();
  3564. this._beforeCameraDrawStage.clear();
  3565. this._beforeRenderTargetDrawStage.clear();
  3566. this._beforeRenderingGroupDrawStage.clear();
  3567. this._beforeRenderingMeshStage.clear();
  3568. this._afterRenderingMeshStage.clear();
  3569. this._afterRenderingGroupDrawStage.clear();
  3570. this._afterCameraDrawStage.clear();
  3571. this._afterRenderTargetDrawStage.clear();
  3572. this._afterRenderStage.clear();
  3573. this._beforeCameraUpdateStage.clear();
  3574. this._beforeClearStage.clear();
  3575. this._gatherRenderTargetsStage.clear();
  3576. this._gatherActiveCameraRenderTargetsStage.clear();
  3577. this._pointerMoveStage.clear();
  3578. this._pointerDownStage.clear();
  3579. this._pointerUpStage.clear();
  3580. for (let component of this._components) {
  3581. component.dispose();
  3582. }
  3583. this.importedMeshesFiles = new Array<string>();
  3584. if (this.stopAllAnimations) {
  3585. this.stopAllAnimations();
  3586. }
  3587. this.resetCachedMaterial();
  3588. // Smart arrays
  3589. if (this.activeCamera) {
  3590. this.activeCamera._activeMeshes.dispose();
  3591. this.activeCamera = null;
  3592. }
  3593. this._activeMeshes.dispose();
  3594. this._renderingManager.dispose();
  3595. this._processedMaterials.dispose();
  3596. this._activeParticleSystems.dispose();
  3597. this._activeSkeletons.dispose();
  3598. this._softwareSkinnedMeshes.dispose();
  3599. this._renderTargets.dispose();
  3600. this._registeredForLateAnimationBindings.dispose();
  3601. this._meshesForIntersections.dispose();
  3602. this._toBeDisposed = [];
  3603. // Abort active requests
  3604. for (let request of this._activeRequests) {
  3605. request.abort();
  3606. }
  3607. // Events
  3608. this.onDisposeObservable.notifyObservers(this);
  3609. this.onDisposeObservable.clear();
  3610. this.onBeforeRenderObservable.clear();
  3611. this.onAfterRenderObservable.clear();
  3612. this.onBeforeRenderTargetsRenderObservable.clear();
  3613. this.onAfterRenderTargetsRenderObservable.clear();
  3614. this.onAfterStepObservable.clear();
  3615. this.onBeforeStepObservable.clear();
  3616. this.onBeforeActiveMeshesEvaluationObservable.clear();
  3617. this.onAfterActiveMeshesEvaluationObservable.clear();
  3618. this.onBeforeParticlesRenderingObservable.clear();
  3619. this.onAfterParticlesRenderingObservable.clear();
  3620. this.onBeforeDrawPhaseObservable.clear();
  3621. this.onAfterDrawPhaseObservable.clear();
  3622. this.onBeforeAnimationsObservable.clear();
  3623. this.onAfterAnimationsObservable.clear();
  3624. this.onDataLoadedObservable.clear();
  3625. this.onBeforeRenderingGroupObservable.clear();
  3626. this.onAfterRenderingGroupObservable.clear();
  3627. this.onMeshImportedObservable.clear();
  3628. this.onBeforeCameraRenderObservable.clear();
  3629. this.onAfterCameraRenderObservable.clear();
  3630. this.onReadyObservable.clear();
  3631. this.onNewCameraAddedObservable.clear();
  3632. this.onCameraRemovedObservable.clear();
  3633. this.onNewLightAddedObservable.clear();
  3634. this.onLightRemovedObservable.clear();
  3635. this.onNewGeometryAddedObservable.clear();
  3636. this.onGeometryRemovedObservable.clear();
  3637. this.onNewTransformNodeAddedObservable.clear();
  3638. this.onTransformNodeRemovedObservable.clear();
  3639. this.onNewMeshAddedObservable.clear();
  3640. this.onMeshRemovedObservable.clear();
  3641. this.onNewSkeletonAddedObservable.clear();
  3642. this.onSkeletonRemovedObservable.clear();
  3643. this.onNewMaterialAddedObservable.clear();
  3644. this.onMaterialRemovedObservable.clear();
  3645. this.onNewTextureAddedObservable.clear();
  3646. this.onTextureRemovedObservable.clear();
  3647. this.onPrePointerObservable.clear();
  3648. this.onPointerObservable.clear();
  3649. this.onPreKeyboardObservable.clear();
  3650. this.onKeyboardObservable.clear();
  3651. this.onActiveCameraChanged.clear();
  3652. this.detachControl();
  3653. // Detach cameras
  3654. var canvas = this._engine.getInputElement();
  3655. if (canvas) {
  3656. var index;
  3657. for (index = 0; index < this.cameras.length; index++) {
  3658. this.cameras[index].detachControl();
  3659. }
  3660. }
  3661. // Release animation groups
  3662. while (this.animationGroups.length) {
  3663. this.animationGroups[0].dispose();
  3664. }
  3665. // Release lights
  3666. while (this.lights.length) {
  3667. this.lights[0].dispose();
  3668. }
  3669. // Release meshes
  3670. while (this.meshes.length) {
  3671. this.meshes[0].dispose(true);
  3672. }
  3673. while (this.transformNodes.length) {
  3674. this.transformNodes[0].dispose(true);
  3675. }
  3676. // Release cameras
  3677. while (this.cameras.length) {
  3678. this.cameras[0].dispose();
  3679. }
  3680. // Release materials
  3681. if (this._defaultMaterial) {
  3682. this._defaultMaterial.dispose();
  3683. }
  3684. while (this.multiMaterials.length) {
  3685. this.multiMaterials[0].dispose();
  3686. }
  3687. while (this.materials.length) {
  3688. this.materials[0].dispose();
  3689. }
  3690. // Release particles
  3691. while (this.particleSystems.length) {
  3692. this.particleSystems[0].dispose();
  3693. }
  3694. // Release postProcesses
  3695. while (this.postProcesses.length) {
  3696. this.postProcesses[0].dispose();
  3697. }
  3698. // Release textures
  3699. while (this.textures.length) {
  3700. this.textures[0].dispose();
  3701. }
  3702. // Release UBO
  3703. this._sceneUbo.dispose();
  3704. if (this._multiviewSceneUbo) {
  3705. this._multiviewSceneUbo.dispose();
  3706. }
  3707. // Post-processes
  3708. this.postProcessManager.dispose();
  3709. // Remove from engine
  3710. index = this._engine.scenes.indexOf(this);
  3711. if (index > -1) {
  3712. this._engine.scenes.splice(index, 1);
  3713. }
  3714. this._engine.wipeCaches(true);
  3715. this._isDisposed = true;
  3716. }
  3717. /**
  3718. * Gets if the scene is already disposed
  3719. */
  3720. public get isDisposed(): boolean {
  3721. return this._isDisposed;
  3722. }
  3723. /**
  3724. * Call this function to reduce memory footprint of the scene.
  3725. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  3726. */
  3727. public clearCachedVertexData(): void {
  3728. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  3729. var mesh = this.meshes[meshIndex];
  3730. var geometry = (<Mesh>mesh).geometry;
  3731. if (geometry) {
  3732. geometry._indices = [];
  3733. for (var vbName in geometry._vertexBuffers) {
  3734. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  3735. continue;
  3736. }
  3737. geometry._vertexBuffers[vbName]._buffer._data = null;
  3738. }
  3739. }
  3740. }
  3741. }
  3742. /**
  3743. * This function will remove the local cached buffer data from texture.
  3744. * It will save memory but will prevent the texture from being rebuilt
  3745. */
  3746. public cleanCachedTextureBuffer(): void {
  3747. for (var baseTexture of this.textures) {
  3748. let buffer = (<Texture>baseTexture)._buffer;
  3749. if (buffer) {
  3750. (<Texture>baseTexture)._buffer = null;
  3751. }
  3752. }
  3753. }
  3754. /**
  3755. * Get the world extend vectors with an optional filter
  3756. *
  3757. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  3758. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  3759. */
  3760. public getWorldExtends(filterPredicate?: (mesh: AbstractMesh) => boolean): { min: Vector3; max: Vector3 } {
  3761. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3762. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3763. filterPredicate = filterPredicate || (() => true);
  3764. this.meshes.filter(filterPredicate).forEach((mesh) => {
  3765. mesh.computeWorldMatrix(true);
  3766. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  3767. return;
  3768. }
  3769. let boundingInfo = mesh.getBoundingInfo();
  3770. var minBox = boundingInfo.boundingBox.minimumWorld;
  3771. var maxBox = boundingInfo.boundingBox.maximumWorld;
  3772. Vector3.CheckExtends(minBox, min, max);
  3773. Vector3.CheckExtends(maxBox, min, max);
  3774. });
  3775. return {
  3776. min: min,
  3777. max: max
  3778. };
  3779. }
  3780. // Picking
  3781. /**
  3782. * Creates a ray that can be used to pick in the scene
  3783. * @param x defines the x coordinate of the origin (on-screen)
  3784. * @param y defines the y coordinate of the origin (on-screen)
  3785. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  3786. * @param camera defines the camera to use for the picking
  3787. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  3788. * @returns a Ray
  3789. */
  3790. public createPickingRay(x: number, y: number, world: Matrix, camera: Nullable<Camera>, cameraViewSpace = false): Ray {
  3791. throw _DevTools.WarnImport("Ray");
  3792. }
  3793. /**
  3794. * Creates a ray that can be used to pick in the scene
  3795. * @param x defines the x coordinate of the origin (on-screen)
  3796. * @param y defines the y coordinate of the origin (on-screen)
  3797. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  3798. * @param result defines the ray where to store the picking ray
  3799. * @param camera defines the camera to use for the picking
  3800. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  3801. * @returns the current scene
  3802. */
  3803. public createPickingRayToRef(x: number, y: number, world: Matrix, result: Ray, camera: Nullable<Camera>, cameraViewSpace = false): Scene {
  3804. throw _DevTools.WarnImport("Ray");
  3805. }
  3806. /**
  3807. * Creates a ray that can be used to pick in the scene
  3808. * @param x defines the x coordinate of the origin (on-screen)
  3809. * @param y defines the y coordinate of the origin (on-screen)
  3810. * @param camera defines the camera to use for the picking
  3811. * @returns a Ray
  3812. */
  3813. public createPickingRayInCameraSpace(x: number, y: number, camera?: Camera): Ray {
  3814. throw _DevTools.WarnImport("Ray");
  3815. }
  3816. /**
  3817. * Creates a ray that can be used to pick in the scene
  3818. * @param x defines the x coordinate of the origin (on-screen)
  3819. * @param y defines the y coordinate of the origin (on-screen)
  3820. * @param result defines the ray where to store the picking ray
  3821. * @param camera defines the camera to use for the picking
  3822. * @returns the current scene
  3823. */
  3824. public createPickingRayInCameraSpaceToRef(x: number, y: number, result: Ray, camera?: Camera): Scene {
  3825. throw _DevTools.WarnImport("Ray");
  3826. }
  3827. /** Launch a ray to try to pick a mesh in the scene
  3828. * @param x position on screen
  3829. * @param y position on screen
  3830. * @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
  3831. * @param fastCheck defines if the first intersection will be used (and not the closest)
  3832. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3833. * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
  3834. * @returns a PickingInfo
  3835. */
  3836. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean,
  3837. fastCheck?: boolean, camera?: Nullable<Camera>,
  3838. trianglePredicate?: TrianglePickingPredicate
  3839. ): Nullable<PickingInfo> {
  3840. // Dummy info if picking as not been imported
  3841. const pi = new PickingInfo();
  3842. pi._pickingUnavailable = true;
  3843. return pi;
  3844. }
  3845. /** Launch a ray to try to pick a mesh in the scene using only bounding information of the main mesh (not using submeshes)
  3846. * @param x position on screen
  3847. * @param y position on screen
  3848. * @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
  3849. * @param fastCheck defines if the first intersection will be used (and not the closest)
  3850. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3851. * @returns a PickingInfo (Please note that some info will not be set like distance, bv, bu and everything that cannot be capture by only using bounding infos)
  3852. */
  3853. public pickWithBoundingInfo(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean,
  3854. fastCheck?: boolean, camera?: Nullable<Camera>): Nullable<PickingInfo> {
  3855. // Dummy info if picking as not been imported
  3856. const pi = new PickingInfo();
  3857. pi._pickingUnavailable = true;
  3858. return pi;
  3859. }
  3860. /** Use the given ray to pick a mesh in the scene
  3861. * @param ray The ray to use to pick meshes
  3862. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  3863. * @param fastCheck defines if the first intersection will be used (and not the closest)
  3864. * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
  3865. * @returns a PickingInfo
  3866. */
  3867. public pickWithRay(ray: Ray, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean,
  3868. trianglePredicate?: TrianglePickingPredicate): Nullable<PickingInfo> {
  3869. throw _DevTools.WarnImport("Ray");
  3870. }
  3871. /**
  3872. * Launch a ray to try to pick a mesh in the scene
  3873. * @param x X position on screen
  3874. * @param y Y position on screen
  3875. * @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
  3876. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  3877. * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
  3878. * @returns an array of PickingInfo
  3879. */
  3880. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera,
  3881. trianglePredicate?: TrianglePickingPredicate): Nullable<PickingInfo[]> {
  3882. throw _DevTools.WarnImport("Ray");
  3883. }
  3884. /**
  3885. * Launch a ray to try to pick a mesh in the scene
  3886. * @param ray Ray to use
  3887. * @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
  3888. * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
  3889. * @returns an array of PickingInfo
  3890. */
  3891. public multiPickWithRay(ray: Ray, predicate: (mesh: AbstractMesh) => boolean, trianglePredicate?: TrianglePickingPredicate): Nullable<PickingInfo[]> {
  3892. throw _DevTools.WarnImport("Ray");
  3893. }
  3894. /**
  3895. * Force the value of meshUnderPointer
  3896. * @param mesh defines the mesh to use
  3897. * @param pointerId optional pointer id when using more than one pointer
  3898. */
  3899. public setPointerOverMesh(mesh: Nullable<AbstractMesh>, pointerId?: number): void {
  3900. this._inputManager.setPointerOverMesh(mesh, pointerId);
  3901. }
  3902. /**
  3903. * Gets the mesh under the pointer
  3904. * @returns a Mesh or null if no mesh is under the pointer
  3905. */
  3906. public getPointerOverMesh(): Nullable<AbstractMesh> {
  3907. return this._inputManager.getPointerOverMesh();
  3908. }
  3909. // Misc.
  3910. /** @hidden */
  3911. public _rebuildGeometries(): void {
  3912. for (var geometry of this.geometries) {
  3913. geometry._rebuild();
  3914. }
  3915. for (var mesh of this.meshes) {
  3916. mesh._rebuild();
  3917. }
  3918. if (this.postProcessManager) {
  3919. this.postProcessManager._rebuild();
  3920. }
  3921. for (let component of this._components) {
  3922. component.rebuild();
  3923. }
  3924. for (var system of this.particleSystems) {
  3925. system.rebuild();
  3926. }
  3927. }
  3928. /** @hidden */
  3929. public _rebuildTextures(): void {
  3930. for (var texture of this.textures) {
  3931. texture._rebuild();
  3932. }
  3933. this.markAllMaterialsAsDirty(Constants.MATERIAL_TextureDirtyFlag);
  3934. }
  3935. // Tags
  3936. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  3937. if (tagsQuery === undefined) {
  3938. // returns the complete list (could be done with Tags.MatchesQuery but no need to have a for-loop here)
  3939. return list;
  3940. }
  3941. var listByTags = [];
  3942. forEach = forEach || ((item: any) => { return; });
  3943. for (var i in list) {
  3944. var item = list[i];
  3945. if (Tags && Tags.MatchesQuery(item, tagsQuery)) {
  3946. listByTags.push(item);
  3947. forEach(item);
  3948. }
  3949. }
  3950. return listByTags;
  3951. }
  3952. /**
  3953. * Get a list of meshes by tags
  3954. * @param tagsQuery defines the tags query to use
  3955. * @param forEach defines a predicate used to filter results
  3956. * @returns an array of Mesh
  3957. */
  3958. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  3959. return this._getByTags(this.meshes, tagsQuery, forEach);
  3960. }
  3961. /**
  3962. * Get a list of cameras by tags
  3963. * @param tagsQuery defines the tags query to use
  3964. * @param forEach defines a predicate used to filter results
  3965. * @returns an array of Camera
  3966. */
  3967. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  3968. return this._getByTags(this.cameras, tagsQuery, forEach);
  3969. }
  3970. /**
  3971. * Get a list of lights by tags
  3972. * @param tagsQuery defines the tags query to use
  3973. * @param forEach defines a predicate used to filter results
  3974. * @returns an array of Light
  3975. */
  3976. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  3977. return this._getByTags(this.lights, tagsQuery, forEach);
  3978. }
  3979. /**
  3980. * Get a list of materials by tags
  3981. * @param tagsQuery defines the tags query to use
  3982. * @param forEach defines a predicate used to filter results
  3983. * @returns an array of Material
  3984. */
  3985. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  3986. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  3987. }
  3988. /**
  3989. * Get a list of transform nodes by tags
  3990. * @param tagsQuery defines the tags query to use
  3991. * @param forEach defines a predicate used to filter results
  3992. * @returns an array of TransformNode
  3993. */
  3994. public getTransformNodesByTags(tagsQuery: string, forEach?: (transform: TransformNode) => void): TransformNode[] {
  3995. return this._getByTags(this.transformNodes, tagsQuery, forEach);
  3996. }
  3997. /**
  3998. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  3999. * This allowed control for front to back rendering or reversly depending of the special needs.
  4000. *
  4001. * @param renderingGroupId The rendering group id corresponding to its index
  4002. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  4003. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  4004. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  4005. */
  4006. public setRenderingOrder(renderingGroupId: number,
  4007. opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  4008. alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null,
  4009. transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null): void {
  4010. this._renderingManager.setRenderingOrder(renderingGroupId,
  4011. opaqueSortCompareFn,
  4012. alphaTestSortCompareFn,
  4013. transparentSortCompareFn);
  4014. }
  4015. /**
  4016. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  4017. *
  4018. * @param renderingGroupId The rendering group id corresponding to its index
  4019. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  4020. * @param depth Automatically clears depth between groups if true and autoClear is true.
  4021. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  4022. */
  4023. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  4024. depth = true,
  4025. stencil = true): void {
  4026. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  4027. }
  4028. /**
  4029. * Gets the current auto clear configuration for one rendering group of the rendering
  4030. * manager.
  4031. * @param index the rendering group index to get the information for
  4032. * @returns The auto clear setup for the requested rendering group
  4033. */
  4034. public getAutoClearDepthStencilSetup(index: number): IRenderingManagerAutoClearSetup {
  4035. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  4036. }
  4037. private _blockMaterialDirtyMechanism = false;
  4038. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  4039. public get blockMaterialDirtyMechanism(): boolean {
  4040. return this._blockMaterialDirtyMechanism;
  4041. }
  4042. public set blockMaterialDirtyMechanism(value: boolean) {
  4043. if (this._blockMaterialDirtyMechanism === value) {
  4044. return;
  4045. }
  4046. this._blockMaterialDirtyMechanism = value;
  4047. if (!value) { // Do a complete update
  4048. this.markAllMaterialsAsDirty(Constants.MATERIAL_AllDirtyFlag);
  4049. }
  4050. }
  4051. /**
  4052. * Will flag all materials as dirty to trigger new shader compilation
  4053. * @param flag defines the flag used to specify which material part must be marked as dirty
  4054. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  4055. */
  4056. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  4057. if (this._blockMaterialDirtyMechanism) {
  4058. return;
  4059. }
  4060. for (var material of this.materials) {
  4061. if (predicate && !predicate(material)) {
  4062. continue;
  4063. }
  4064. material.markAsDirty(flag);
  4065. }
  4066. }
  4067. /** @hidden */
  4068. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (ev: ProgressEvent) => void, useOfflineSupport?: boolean, useArrayBuffer?: boolean, onError?: (request?: WebRequest, exception?: LoadFileError) => void): IFileRequest {
  4069. const request = FileTools.LoadFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError);
  4070. this._activeRequests.push(request);
  4071. request.onCompleteObservable.add((request) => {
  4072. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4073. });
  4074. return request;
  4075. }
  4076. /** @hidden */
  4077. public _loadFileAsync(url: string, onProgress?: (data: any) => void, useOfflineSupport?: boolean, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  4078. return new Promise((resolve, reject) => {
  4079. this._loadFile(url, (data) => {
  4080. resolve(data);
  4081. }, onProgress, useOfflineSupport, useArrayBuffer, (request, exception) => {
  4082. reject(exception);
  4083. });
  4084. });
  4085. }
  4086. /** @hidden */
  4087. public _requestFile(url: string, onSuccess: (data: string | ArrayBuffer, request?: WebRequest) => void, onProgress?: (ev: ProgressEvent) => void, useOfflineSupport?: boolean, useArrayBuffer?: boolean, onError?: (error: RequestFileError) => void, onOpened?: (request: WebRequest) => void): IFileRequest {
  4088. const request = FileTools.RequestFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError, onOpened);
  4089. this._activeRequests.push(request);
  4090. request.onCompleteObservable.add((request) => {
  4091. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4092. });
  4093. return request;
  4094. }
  4095. /** @hidden */
  4096. public _requestFileAsync(url: string, onProgress?: (ev: ProgressEvent) => void, useOfflineSupport?: boolean, useArrayBuffer?: boolean, onOpened?: (request: WebRequest) => void): Promise<string | ArrayBuffer> {
  4097. return new Promise((resolve, reject) => {
  4098. this._requestFile(url, (data) => {
  4099. resolve(data);
  4100. }, onProgress, useOfflineSupport, useArrayBuffer, (error) => {
  4101. reject(error);
  4102. }, onOpened);
  4103. });
  4104. }
  4105. /** @hidden */
  4106. public _readFile(file: File, onSuccess: (data: string | ArrayBuffer) => void, onProgress?: (ev: ProgressEvent) => any, useArrayBuffer?: boolean, onError?: (error: ReadFileError) => void): IFileRequest {
  4107. const request = FileTools.ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError);
  4108. this._activeRequests.push(request);
  4109. request.onCompleteObservable.add((request) => {
  4110. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4111. });
  4112. return request;
  4113. }
  4114. /** @hidden */
  4115. public _readFileAsync(file: File, onProgress?: (ev: ProgressEvent) => any, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  4116. return new Promise((resolve, reject) => {
  4117. this._readFile(file, (data) => {
  4118. resolve(data);
  4119. }, onProgress, useArrayBuffer, (error) => {
  4120. reject(error);
  4121. });
  4122. });
  4123. }
  4124. }