babylon.scene.ts 240 KB

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