babylon.scene.ts 246 KB

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