scene.ts 209 KB

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