babylon.scene.ts 241 KB

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