babylon.scene.ts 252 KB

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