scene.ts 227 KB

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