babylon.max.js 2.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. // Operators
  62. Color3.prototype.toArray = function (array, index) {
  63. if (index === undefined) {
  64. index = 0;
  65. }
  66. array[index] = this.r;
  67. array[index + 1] = this.g;
  68. array[index + 2] = this.b;
  69. return this;
  70. };
  71. Color3.prototype.toColor4 = function (alpha) {
  72. if (alpha === void 0) { alpha = 1; }
  73. return new Color4(this.r, this.g, this.b, alpha);
  74. };
  75. Color3.prototype.asArray = function () {
  76. var result = [];
  77. this.toArray(result, 0);
  78. return result;
  79. };
  80. Color3.prototype.toLuminance = function () {
  81. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  82. };
  83. Color3.prototype.multiply = function (otherColor) {
  84. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  85. };
  86. Color3.prototype.multiplyToRef = function (otherColor, result) {
  87. result.r = this.r * otherColor.r;
  88. result.g = this.g * otherColor.g;
  89. result.b = this.b * otherColor.b;
  90. return this;
  91. };
  92. Color3.prototype.equals = function (otherColor) {
  93. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  94. };
  95. Color3.prototype.equalsFloats = function (r, g, b) {
  96. return this.r === r && this.g === g && this.b === b;
  97. };
  98. Color3.prototype.scale = function (scale) {
  99. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  100. };
  101. Color3.prototype.scaleToRef = function (scale, result) {
  102. result.r = this.r * scale;
  103. result.g = this.g * scale;
  104. result.b = this.b * scale;
  105. return this;
  106. };
  107. Color3.prototype.add = function (otherColor) {
  108. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  109. };
  110. Color3.prototype.addToRef = function (otherColor, result) {
  111. result.r = this.r + otherColor.r;
  112. result.g = this.g + otherColor.g;
  113. result.b = this.b + otherColor.b;
  114. return this;
  115. };
  116. Color3.prototype.subtract = function (otherColor) {
  117. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  118. };
  119. Color3.prototype.subtractToRef = function (otherColor, result) {
  120. result.r = this.r - otherColor.r;
  121. result.g = this.g - otherColor.g;
  122. result.b = this.b - otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.clone = function () {
  126. return new Color3(this.r, this.g, this.b);
  127. };
  128. Color3.prototype.copyFrom = function (source) {
  129. this.r = source.r;
  130. this.g = source.g;
  131. this.b = source.b;
  132. return this;
  133. };
  134. Color3.prototype.copyFromFloats = function (r, g, b) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. return this;
  139. };
  140. Color3.prototype.toHexString = function () {
  141. var intR = (this.r * 255) | 0;
  142. var intG = (this.g * 255) | 0;
  143. var intB = (this.b * 255) | 0;
  144. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  145. };
  146. Color3.prototype.toLinearSpace = function () {
  147. var convertedColor = new Color3();
  148. this.toLinearSpaceToRef(convertedColor);
  149. return convertedColor;
  150. };
  151. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  152. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  153. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  154. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  155. return this;
  156. };
  157. Color3.prototype.toGammaSpace = function () {
  158. var convertedColor = new Color3();
  159. this.toGammaSpaceToRef(convertedColor);
  160. return convertedColor;
  161. };
  162. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  163. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  164. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  165. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  166. return this;
  167. };
  168. // Statics
  169. Color3.FromHexString = function (hex) {
  170. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  171. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  172. return new Color3(0, 0, 0);
  173. }
  174. var r = parseInt(hex.substring(1, 3), 16);
  175. var g = parseInt(hex.substring(3, 5), 16);
  176. var b = parseInt(hex.substring(5, 7), 16);
  177. return Color3.FromInts(r, g, b);
  178. };
  179. Color3.FromArray = function (array, offset) {
  180. if (offset === void 0) { offset = 0; }
  181. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  182. };
  183. Color3.FromInts = function (r, g, b) {
  184. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  185. };
  186. Color3.Lerp = function (start, end, amount) {
  187. var r = start.r + ((end.r - start.r) * amount);
  188. var g = start.g + ((end.g - start.g) * amount);
  189. var b = start.b + ((end.b - start.b) * amount);
  190. return new Color3(r, g, b);
  191. };
  192. Color3.Red = function () { return new Color3(1, 0, 0); };
  193. Color3.Green = function () { return new Color3(0, 1, 0); };
  194. Color3.Blue = function () { return new Color3(0, 0, 1); };
  195. Color3.Black = function () { return new Color3(0, 0, 0); };
  196. Color3.White = function () { return new Color3(1, 1, 1); };
  197. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  198. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  199. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  200. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  201. return Color3;
  202. })();
  203. BABYLON.Color3 = Color3;
  204. var Color4 = (function () {
  205. function Color4(r, g, b, a) {
  206. this.r = r;
  207. this.g = g;
  208. this.b = b;
  209. this.a = a;
  210. }
  211. // Operators
  212. Color4.prototype.addInPlace = function (right) {
  213. this.r += right.r;
  214. this.g += right.g;
  215. this.b += right.b;
  216. this.a += right.a;
  217. return this;
  218. };
  219. Color4.prototype.asArray = function () {
  220. var result = [];
  221. this.toArray(result, 0);
  222. return result;
  223. };
  224. Color4.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.r;
  229. array[index + 1] = this.g;
  230. array[index + 2] = this.b;
  231. array[index + 3] = this.a;
  232. return this;
  233. };
  234. Color4.prototype.add = function (right) {
  235. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  236. };
  237. Color4.prototype.subtract = function (right) {
  238. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  239. };
  240. Color4.prototype.subtractToRef = function (right, result) {
  241. result.r = this.r - right.r;
  242. result.g = this.g - right.g;
  243. result.b = this.b - right.b;
  244. result.a = this.a - right.a;
  245. return this;
  246. };
  247. Color4.prototype.scale = function (scale) {
  248. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  249. };
  250. Color4.prototype.scaleToRef = function (scale, result) {
  251. result.r = this.r * scale;
  252. result.g = this.g * scale;
  253. result.b = this.b * scale;
  254. result.a = this.a * scale;
  255. return this;
  256. };
  257. Color4.prototype.toString = function () {
  258. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  259. };
  260. Color4.prototype.clone = function () {
  261. return new Color4(this.r, this.g, this.b, this.a);
  262. };
  263. Color4.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. this.a = source.a;
  268. return this;
  269. };
  270. Color4.prototype.toHexString = function () {
  271. var intR = (this.r * 255) | 0;
  272. var intG = (this.g * 255) | 0;
  273. var intB = (this.b * 255) | 0;
  274. var intA = (this.a * 255) | 0;
  275. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  276. };
  277. // Statics
  278. Color4.FromHexString = function (hex) {
  279. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  280. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  281. return new Color4(0, 0, 0, 0);
  282. }
  283. var r = parseInt(hex.substring(1, 3), 16);
  284. var g = parseInt(hex.substring(3, 5), 16);
  285. var b = parseInt(hex.substring(5, 7), 16);
  286. var a = parseInt(hex.substring(7, 9), 16);
  287. return Color4.FromInts(r, g, b, a);
  288. };
  289. Color4.Lerp = function (left, right, amount) {
  290. var result = new Color4(0, 0, 0, 0);
  291. Color4.LerpToRef(left, right, amount, result);
  292. return result;
  293. };
  294. Color4.LerpToRef = function (left, right, amount, result) {
  295. result.r = left.r + (right.r - left.r) * amount;
  296. result.g = left.g + (right.g - left.g) * amount;
  297. result.b = left.b + (right.b - left.b) * amount;
  298. result.a = left.a + (right.a - left.a) * amount;
  299. };
  300. Color4.FromArray = function (array, offset) {
  301. if (offset === void 0) { offset = 0; }
  302. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  303. };
  304. Color4.FromInts = function (r, g, b, a) {
  305. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  306. };
  307. Color4.CheckColors4 = function (colors, count) {
  308. // Check if color3 was used
  309. if (colors.length === count * 3) {
  310. var colors4 = [];
  311. for (var index = 0; index < colors.length; index += 3) {
  312. var newIndex = (index / 3) * 4;
  313. colors4[newIndex] = colors[index];
  314. colors4[newIndex + 1] = colors[index + 1];
  315. colors4[newIndex + 2] = colors[index + 2];
  316. colors4[newIndex + 3] = 1.0;
  317. }
  318. return colors4;
  319. }
  320. return colors;
  321. };
  322. return Color4;
  323. })();
  324. BABYLON.Color4 = Color4;
  325. var Vector2 = (function () {
  326. function Vector2(x, y) {
  327. this.x = x;
  328. this.y = y;
  329. }
  330. Vector2.prototype.toString = function () {
  331. return "{X: " + this.x + " Y:" + this.y + "}";
  332. };
  333. // Operators
  334. Vector2.prototype.toArray = function (array, index) {
  335. if (index === void 0) { index = 0; }
  336. array[index] = this.x;
  337. array[index + 1] = this.y;
  338. return this;
  339. };
  340. Vector2.prototype.asArray = function () {
  341. var result = [];
  342. this.toArray(result, 0);
  343. return result;
  344. };
  345. Vector2.prototype.copyFrom = function (source) {
  346. this.x = source.x;
  347. this.y = source.y;
  348. return this;
  349. };
  350. Vector2.prototype.copyFromFloats = function (x, y) {
  351. this.x = x;
  352. this.y = y;
  353. return this;
  354. };
  355. Vector2.prototype.add = function (otherVector) {
  356. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  357. };
  358. Vector2.prototype.addVector3 = function (otherVector) {
  359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  360. };
  361. Vector2.prototype.subtract = function (otherVector) {
  362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  363. };
  364. Vector2.prototype.subtractInPlace = function (otherVector) {
  365. this.x -= otherVector.x;
  366. this.y -= otherVector.y;
  367. return this;
  368. };
  369. Vector2.prototype.multiplyInPlace = function (otherVector) {
  370. this.x *= otherVector.x;
  371. this.y *= otherVector.y;
  372. return this;
  373. };
  374. Vector2.prototype.multiply = function (otherVector) {
  375. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  376. };
  377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  378. result.x = this.x * otherVector.x;
  379. result.y = this.y * otherVector.y;
  380. return this;
  381. };
  382. Vector2.prototype.multiplyByFloats = function (x, y) {
  383. return new Vector2(this.x * x, this.y * y);
  384. };
  385. Vector2.prototype.divide = function (otherVector) {
  386. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  387. };
  388. Vector2.prototype.divideToRef = function (otherVector, result) {
  389. result.x = this.x / otherVector.x;
  390. result.y = this.y / otherVector.y;
  391. return this;
  392. };
  393. Vector2.prototype.negate = function () {
  394. return new Vector2(-this.x, -this.y);
  395. };
  396. Vector2.prototype.scaleInPlace = function (scale) {
  397. this.x *= scale;
  398. this.y *= scale;
  399. return this;
  400. };
  401. Vector2.prototype.scale = function (scale) {
  402. return new Vector2(this.x * scale, this.y * scale);
  403. };
  404. Vector2.prototype.equals = function (otherVector) {
  405. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  406. };
  407. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  408. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  409. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  410. };
  411. // Properties
  412. Vector2.prototype.length = function () {
  413. return Math.sqrt(this.x * this.x + this.y * this.y);
  414. };
  415. Vector2.prototype.lengthSquared = function () {
  416. return (this.x * this.x + this.y * this.y);
  417. };
  418. // Methods
  419. Vector2.prototype.normalize = function () {
  420. var len = this.length();
  421. if (len === 0)
  422. return this;
  423. var num = 1.0 / len;
  424. this.x *= num;
  425. this.y *= num;
  426. return this;
  427. };
  428. Vector2.prototype.clone = function () {
  429. return new Vector2(this.x, this.y);
  430. };
  431. // Statics
  432. Vector2.Zero = function () {
  433. return new Vector2(0, 0);
  434. };
  435. Vector2.FromArray = function (array, offset) {
  436. if (offset === void 0) { offset = 0; }
  437. return new Vector2(array[offset], array[offset + 1]);
  438. };
  439. Vector2.FromArrayToRef = function (array, offset, result) {
  440. result.x = array[offset];
  441. result.y = array[offset + 1];
  442. };
  443. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  444. var squared = amount * amount;
  445. var cubed = amount * squared;
  446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Clamp = function (value, min, max) {
  455. var x = value.x;
  456. x = (x > max.x) ? max.x : x;
  457. x = (x < min.x) ? min.x : x;
  458. var y = value.y;
  459. y = (y > max.y) ? max.y : y;
  460. y = (y < min.y) ? min.y : y;
  461. return new Vector2(x, y);
  462. };
  463. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  464. var squared = amount * amount;
  465. var cubed = amount * squared;
  466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  468. var part3 = (cubed - (2.0 * squared)) + amount;
  469. var part4 = cubed - squared;
  470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  472. return new Vector2(x, y);
  473. };
  474. Vector2.Lerp = function (start, end, amount) {
  475. var x = start.x + ((end.x - start.x) * amount);
  476. var y = start.y + ((end.y - start.y) * amount);
  477. return new Vector2(x, y);
  478. };
  479. Vector2.Dot = function (left, right) {
  480. return left.x * right.x + left.y * right.y;
  481. };
  482. Vector2.Normalize = function (vector) {
  483. var newVector = vector.clone();
  484. newVector.normalize();
  485. return newVector;
  486. };
  487. Vector2.Minimize = function (left, right) {
  488. var x = (left.x < right.x) ? left.x : right.x;
  489. var y = (left.y < right.y) ? left.y : right.y;
  490. return new Vector2(x, y);
  491. };
  492. Vector2.Maximize = function (left, right) {
  493. var x = (left.x > right.x) ? left.x : right.x;
  494. var y = (left.y > right.y) ? left.y : right.y;
  495. return new Vector2(x, y);
  496. };
  497. Vector2.Transform = function (vector, transformation) {
  498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  500. return new Vector2(x, y);
  501. };
  502. Vector2.Distance = function (value1, value2) {
  503. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  504. };
  505. Vector2.DistanceSquared = function (value1, value2) {
  506. var x = value1.x - value2.x;
  507. var y = value1.y - value2.y;
  508. return (x * x) + (y * y);
  509. };
  510. return Vector2;
  511. })();
  512. BABYLON.Vector2 = Vector2;
  513. var Vector3 = (function () {
  514. function Vector3(x, y, z) {
  515. this.x = x;
  516. this.y = y;
  517. this.z = z;
  518. }
  519. Vector3.prototype.toString = function () {
  520. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  521. };
  522. // Operators
  523. Vector3.prototype.asArray = function () {
  524. var result = [];
  525. this.toArray(result, 0);
  526. return result;
  527. };
  528. Vector3.prototype.toArray = function (array, index) {
  529. if (index === void 0) { index = 0; }
  530. array[index] = this.x;
  531. array[index + 1] = this.y;
  532. array[index + 2] = this.z;
  533. return this;
  534. };
  535. Vector3.prototype.toQuaternion = function () {
  536. var result = new Quaternion(0, 0, 0, 1);
  537. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  538. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  539. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  540. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  541. var cosy = Math.cos(this.y * 0.5);
  542. var siny = Math.sin(this.y * 0.5);
  543. result.x = coszMinusx * siny;
  544. result.y = -sinzMinusx * siny;
  545. result.z = sinxPlusz * cosy;
  546. result.w = cosxPlusz * cosy;
  547. return result;
  548. };
  549. Vector3.prototype.addInPlace = function (otherVector) {
  550. this.x += otherVector.x;
  551. this.y += otherVector.y;
  552. this.z += otherVector.z;
  553. return this;
  554. };
  555. Vector3.prototype.add = function (otherVector) {
  556. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  557. };
  558. Vector3.prototype.addToRef = function (otherVector, result) {
  559. result.x = this.x + otherVector.x;
  560. result.y = this.y + otherVector.y;
  561. result.z = this.z + otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtractInPlace = function (otherVector) {
  565. this.x -= otherVector.x;
  566. this.y -= otherVector.y;
  567. this.z -= otherVector.z;
  568. return this;
  569. };
  570. Vector3.prototype.subtract = function (otherVector) {
  571. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  572. };
  573. Vector3.prototype.subtractToRef = function (otherVector, result) {
  574. result.x = this.x - otherVector.x;
  575. result.y = this.y - otherVector.y;
  576. result.z = this.z - otherVector.z;
  577. return this;
  578. };
  579. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  580. return new Vector3(this.x - x, this.y - y, this.z - z);
  581. };
  582. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  583. result.x = this.x - x;
  584. result.y = this.y - y;
  585. result.z = this.z - z;
  586. return this;
  587. };
  588. Vector3.prototype.negate = function () {
  589. return new Vector3(-this.x, -this.y, -this.z);
  590. };
  591. Vector3.prototype.scaleInPlace = function (scale) {
  592. this.x *= scale;
  593. this.y *= scale;
  594. this.z *= scale;
  595. return this;
  596. };
  597. Vector3.prototype.scale = function (scale) {
  598. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  599. };
  600. Vector3.prototype.scaleToRef = function (scale, result) {
  601. result.x = this.x * scale;
  602. result.y = this.y * scale;
  603. result.z = this.z * scale;
  604. };
  605. Vector3.prototype.equals = function (otherVector) {
  606. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  607. };
  608. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  609. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  610. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  611. };
  612. Vector3.prototype.equalsToFloats = function (x, y, z) {
  613. return this.x === x && this.y === y && this.z === z;
  614. };
  615. Vector3.prototype.multiplyInPlace = function (otherVector) {
  616. this.x *= otherVector.x;
  617. this.y *= otherVector.y;
  618. this.z *= otherVector.z;
  619. return this;
  620. };
  621. Vector3.prototype.multiply = function (otherVector) {
  622. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  623. };
  624. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  625. result.x = this.x * otherVector.x;
  626. result.y = this.y * otherVector.y;
  627. result.z = this.z * otherVector.z;
  628. return this;
  629. };
  630. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  631. return new Vector3(this.x * x, this.y * y, this.z * z);
  632. };
  633. Vector3.prototype.divide = function (otherVector) {
  634. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  635. };
  636. Vector3.prototype.divideToRef = function (otherVector, result) {
  637. result.x = this.x / otherVector.x;
  638. result.y = this.y / otherVector.y;
  639. result.z = this.z / otherVector.z;
  640. return this;
  641. };
  642. Vector3.prototype.MinimizeInPlace = function (other) {
  643. if (other.x < this.x)
  644. this.x = other.x;
  645. if (other.y < this.y)
  646. this.y = other.y;
  647. if (other.z < this.z)
  648. this.z = other.z;
  649. return this;
  650. };
  651. Vector3.prototype.MaximizeInPlace = function (other) {
  652. if (other.x > this.x)
  653. this.x = other.x;
  654. if (other.y > this.y)
  655. this.y = other.y;
  656. if (other.z > this.z)
  657. this.z = other.z;
  658. return this;
  659. };
  660. // Properties
  661. Vector3.prototype.length = function () {
  662. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  663. };
  664. Vector3.prototype.lengthSquared = function () {
  665. return (this.x * this.x + this.y * this.y + this.z * this.z);
  666. };
  667. // Methods
  668. Vector3.prototype.normalize = function () {
  669. var len = this.length();
  670. if (len === 0 || len === 1.0)
  671. return this;
  672. var num = 1.0 / len;
  673. this.x *= num;
  674. this.y *= num;
  675. this.z *= num;
  676. return this;
  677. };
  678. Vector3.prototype.clone = function () {
  679. return new Vector3(this.x, this.y, this.z);
  680. };
  681. Vector3.prototype.copyFrom = function (source) {
  682. this.x = source.x;
  683. this.y = source.y;
  684. this.z = source.z;
  685. return this;
  686. };
  687. Vector3.prototype.copyFromFloats = function (x, y, z) {
  688. this.x = x;
  689. this.y = y;
  690. this.z = z;
  691. return this;
  692. };
  693. // Statics
  694. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  695. var d0 = Vector3.Dot(vector0, axis) - size;
  696. var d1 = Vector3.Dot(vector1, axis) - size;
  697. var s = d0 / (d0 - d1);
  698. return s;
  699. };
  700. Vector3.FromArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromFloatArray = function (array, offset) {
  707. if (!offset) {
  708. offset = 0;
  709. }
  710. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  711. };
  712. Vector3.FromArrayToRef = function (array, offset, result) {
  713. result.x = array[offset];
  714. result.y = array[offset + 1];
  715. result.z = array[offset + 2];
  716. };
  717. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  718. result.x = array[offset];
  719. result.y = array[offset + 1];
  720. result.z = array[offset + 2];
  721. };
  722. Vector3.FromFloatsToRef = function (x, y, z, result) {
  723. result.x = x;
  724. result.y = y;
  725. result.z = z;
  726. };
  727. Vector3.Zero = function () {
  728. return new Vector3(0, 0, 0);
  729. };
  730. Vector3.Up = function () {
  731. return new Vector3(0, 1.0, 0);
  732. };
  733. Vector3.TransformCoordinates = function (vector, transformation) {
  734. var result = Vector3.Zero();
  735. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  736. return result;
  737. };
  738. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  739. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  740. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  741. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  742. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  743. result.x = x / w;
  744. result.y = y / w;
  745. result.z = z / w;
  746. };
  747. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  748. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  749. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  750. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  751. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  752. result.x = rx / rw;
  753. result.y = ry / rw;
  754. result.z = rz / rw;
  755. };
  756. Vector3.TransformNormal = function (vector, transformation) {
  757. var result = Vector3.Zero();
  758. Vector3.TransformNormalToRef(vector, transformation, result);
  759. return result;
  760. };
  761. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  762. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  763. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  764. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  765. };
  766. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  767. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  768. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  769. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  770. };
  771. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  772. var squared = amount * amount;
  773. var cubed = amount * squared;
  774. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  775. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  776. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  777. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  778. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  779. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  780. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  781. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  782. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  783. return new Vector3(x, y, z);
  784. };
  785. Vector3.Clamp = function (value, min, max) {
  786. var x = value.x;
  787. x = (x > max.x) ? max.x : x;
  788. x = (x < min.x) ? min.x : x;
  789. var y = value.y;
  790. y = (y > max.y) ? max.y : y;
  791. y = (y < min.y) ? min.y : y;
  792. var z = value.z;
  793. z = (z > max.z) ? max.z : z;
  794. z = (z < min.z) ? min.z : z;
  795. return new Vector3(x, y, z);
  796. };
  797. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  798. var squared = amount * amount;
  799. var cubed = amount * squared;
  800. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  801. var part2 = (-2.0 * cubed) + (3.0 * squared);
  802. var part3 = (cubed - (2.0 * squared)) + amount;
  803. var part4 = cubed - squared;
  804. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  805. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  806. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Lerp = function (start, end, amount) {
  810. var x = start.x + ((end.x - start.x) * amount);
  811. var y = start.y + ((end.y - start.y) * amount);
  812. var z = start.z + ((end.z - start.z) * amount);
  813. return new Vector3(x, y, z);
  814. };
  815. Vector3.Dot = function (left, right) {
  816. return (left.x * right.x + left.y * right.y + left.z * right.z);
  817. };
  818. Vector3.Cross = function (left, right) {
  819. var result = Vector3.Zero();
  820. Vector3.CrossToRef(left, right, result);
  821. return result;
  822. };
  823. Vector3.CrossToRef = function (left, right, result) {
  824. result.x = left.y * right.z - left.z * right.y;
  825. result.y = left.z * right.x - left.x * right.z;
  826. result.z = left.x * right.y - left.y * right.x;
  827. };
  828. Vector3.Normalize = function (vector) {
  829. var result = Vector3.Zero();
  830. Vector3.NormalizeToRef(vector, result);
  831. return result;
  832. };
  833. Vector3.NormalizeToRef = function (vector, result) {
  834. result.copyFrom(vector);
  835. result.normalize();
  836. };
  837. Vector3.Project = function (vector, world, transform, viewport) {
  838. var cw = viewport.width;
  839. var ch = viewport.height;
  840. var cx = viewport.x;
  841. var cy = viewport.y;
  842. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  843. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  844. return Vector3.TransformCoordinates(vector, finalMatrix);
  845. };
  846. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  847. var matrix = world.multiply(transform);
  848. matrix.invert();
  849. source.x = source.x / viewportWidth * 2 - 1;
  850. source.y = -(source.y / viewportHeight * 2 - 1);
  851. var vector = Vector3.TransformCoordinates(source, matrix);
  852. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  853. if (MathTools.WithinEpsilon(num, 1.0)) {
  854. vector = vector.scale(1.0 / num);
  855. }
  856. return vector;
  857. };
  858. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  859. var matrix = world.multiply(view).multiply(projection);
  860. matrix.invert();
  861. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  862. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  863. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  864. if (MathTools.WithinEpsilon(num, 1.0)) {
  865. vector = vector.scale(1.0 / num);
  866. }
  867. return vector;
  868. };
  869. Vector3.Minimize = function (left, right) {
  870. var min = left.clone();
  871. min.MinimizeInPlace(right);
  872. return min;
  873. };
  874. Vector3.Maximize = function (left, right) {
  875. var max = left.clone();
  876. max.MaximizeInPlace(right);
  877. return max;
  878. };
  879. Vector3.Distance = function (value1, value2) {
  880. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  881. };
  882. Vector3.DistanceSquared = function (value1, value2) {
  883. var x = value1.x - value2.x;
  884. var y = value1.y - value2.y;
  885. var z = value1.z - value2.z;
  886. return (x * x) + (y * y) + (z * z);
  887. };
  888. Vector3.Center = function (value1, value2) {
  889. var center = value1.add(value2);
  890. center.scaleInPlace(0.5);
  891. return center;
  892. };
  893. /**
  894. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  895. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  896. * to something in order to rotate it from its local system to the given target system.
  897. */
  898. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  899. var rotation = Vector3.Zero();
  900. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  901. return rotation;
  902. };
  903. /**
  904. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  905. */
  906. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  907. var u = axis1.normalize();
  908. var w = axis3.normalize();
  909. // world axis
  910. var X = Axis.X;
  911. var Y = Axis.Y;
  912. // equation unknowns and vars
  913. var yaw = 0.0;
  914. var pitch = 0.0;
  915. var roll = 0.0;
  916. var x = 0.0;
  917. var y = 0.0;
  918. var z = 0.0;
  919. var t = 0.0;
  920. var sign = -1.0;
  921. var nbRevert = 0;
  922. var cross = Tmp.Vector3[0];
  923. var dot = 0.0;
  924. // step 1 : rotation around w
  925. // Rv3(u) = u1, and u1 belongs to plane xOz
  926. // Rv3(w) = w1 = w invariant
  927. var u1 = Tmp.Vector3[1];
  928. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  929. z = 1.0;
  930. }
  931. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  932. x = 1.0;
  933. }
  934. else {
  935. t = w.z / w.x;
  936. x = -t * Math.sqrt(1 / (1 + t * t));
  937. z = Math.sqrt(1 / (1 + t * t));
  938. }
  939. u1.x = x;
  940. u1.y = y;
  941. u1.z = z;
  942. u1.normalize();
  943. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(w, cross) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u, u1);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. roll = Math.acos(dot) * sign;
  951. if (Vector3.Dot(u1, X) < 0) {
  952. roll = Math.PI + roll;
  953. u1 = u1.scaleInPlace(-1);
  954. nbRevert++;
  955. }
  956. // step 2 : rotate around u1
  957. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  958. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  959. var w2 = Tmp.Vector3[2];
  960. var v2 = Tmp.Vector3[3];
  961. x = 0.0;
  962. y = 0.0;
  963. z = 0.0;
  964. sign = -1.0;
  965. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  966. x = 1.0;
  967. }
  968. else {
  969. t = u1.z / u1.x;
  970. x = -t * Math.sqrt(1 / (1 + t * t));
  971. z = Math.sqrt(1 / (1 + t * t));
  972. }
  973. w2.x = x;
  974. w2.y = y;
  975. w2.z = z;
  976. w2.normalize();
  977. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  978. v2.normalize();
  979. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  980. cross.normalize();
  981. if (Vector3.Dot(u1, cross) < 0) {
  982. sign = 1.0;
  983. }
  984. dot = Vector3.Dot(w, w2);
  985. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  986. pitch = Math.acos(dot) * sign;
  987. if (Vector3.Dot(v2, Y) < 0) {
  988. pitch = Math.PI + pitch;
  989. nbRevert++;
  990. }
  991. // step 3 : rotate around v2
  992. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  993. sign = -1.0;
  994. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  995. cross.normalize();
  996. if (Vector3.Dot(cross, Y) < 0) {
  997. sign = 1.0;
  998. }
  999. dot = Vector3.Dot(u1, X);
  1000. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1001. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1002. if (dot < 0 && nbRevert < 2) {
  1003. yaw = Math.PI + yaw;
  1004. }
  1005. ref.x = pitch;
  1006. ref.y = yaw;
  1007. ref.z = roll;
  1008. };
  1009. return Vector3;
  1010. })();
  1011. BABYLON.Vector3 = Vector3;
  1012. //Vector4 class created for EulerAngle class conversion to Quaternion
  1013. var Vector4 = (function () {
  1014. function Vector4(x, y, z, w) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. this.w = w;
  1019. }
  1020. Vector4.prototype.toString = function () {
  1021. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1022. };
  1023. // Operators
  1024. Vector4.prototype.asArray = function () {
  1025. var result = [];
  1026. this.toArray(result, 0);
  1027. return result;
  1028. };
  1029. Vector4.prototype.toArray = function (array, index) {
  1030. if (index === undefined) {
  1031. index = 0;
  1032. }
  1033. array[index] = this.x;
  1034. array[index + 1] = this.y;
  1035. array[index + 2] = this.z;
  1036. array[index + 3] = this.w;
  1037. return this;
  1038. };
  1039. Vector4.prototype.addInPlace = function (otherVector) {
  1040. this.x += otherVector.x;
  1041. this.y += otherVector.y;
  1042. this.z += otherVector.z;
  1043. this.w += otherVector.w;
  1044. return this;
  1045. };
  1046. Vector4.prototype.add = function (otherVector) {
  1047. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1048. };
  1049. Vector4.prototype.addToRef = function (otherVector, result) {
  1050. result.x = this.x + otherVector.x;
  1051. result.y = this.y + otherVector.y;
  1052. result.z = this.z + otherVector.z;
  1053. result.w = this.w + otherVector.w;
  1054. return this;
  1055. };
  1056. Vector4.prototype.subtractInPlace = function (otherVector) {
  1057. this.x -= otherVector.x;
  1058. this.y -= otherVector.y;
  1059. this.z -= otherVector.z;
  1060. this.w -= otherVector.w;
  1061. return this;
  1062. };
  1063. Vector4.prototype.subtract = function (otherVector) {
  1064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1065. };
  1066. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1067. result.x = this.x - otherVector.x;
  1068. result.y = this.y - otherVector.y;
  1069. result.z = this.z - otherVector.z;
  1070. result.w = this.w - otherVector.w;
  1071. return this;
  1072. };
  1073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1075. };
  1076. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1077. result.x = this.x - x;
  1078. result.y = this.y - y;
  1079. result.z = this.z - z;
  1080. result.w = this.w - w;
  1081. return this;
  1082. };
  1083. Vector4.prototype.negate = function () {
  1084. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1085. };
  1086. Vector4.prototype.scaleInPlace = function (scale) {
  1087. this.x *= scale;
  1088. this.y *= scale;
  1089. this.z *= scale;
  1090. this.w *= scale;
  1091. return this;
  1092. };
  1093. Vector4.prototype.scale = function (scale) {
  1094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1095. };
  1096. Vector4.prototype.scaleToRef = function (scale, result) {
  1097. result.x = this.x * scale;
  1098. result.y = this.y * scale;
  1099. result.z = this.z * scale;
  1100. result.w = this.w * scale;
  1101. };
  1102. Vector4.prototype.equals = function (otherVector) {
  1103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1104. };
  1105. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1106. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1107. return otherVector
  1108. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1109. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1110. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1111. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1112. };
  1113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1114. return this.x === x && this.y === y && this.z === z && this.w === w;
  1115. };
  1116. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1117. this.x *= otherVector.x;
  1118. this.y *= otherVector.y;
  1119. this.z *= otherVector.z;
  1120. this.w *= otherVector.w;
  1121. return this;
  1122. };
  1123. Vector4.prototype.multiply = function (otherVector) {
  1124. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1125. };
  1126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1127. result.x = this.x * otherVector.x;
  1128. result.y = this.y * otherVector.y;
  1129. result.z = this.z * otherVector.z;
  1130. result.w = this.w * otherVector.w;
  1131. return this;
  1132. };
  1133. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1134. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1135. };
  1136. Vector4.prototype.divide = function (otherVector) {
  1137. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1138. };
  1139. Vector4.prototype.divideToRef = function (otherVector, result) {
  1140. result.x = this.x / otherVector.x;
  1141. result.y = this.y / otherVector.y;
  1142. result.z = this.z / otherVector.z;
  1143. result.w = this.w / otherVector.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.MinimizeInPlace = function (other) {
  1147. if (other.x < this.x)
  1148. this.x = other.x;
  1149. if (other.y < this.y)
  1150. this.y = other.y;
  1151. if (other.z < this.z)
  1152. this.z = other.z;
  1153. if (other.w < this.w)
  1154. this.w = other.w;
  1155. return this;
  1156. };
  1157. Vector4.prototype.MaximizeInPlace = function (other) {
  1158. if (other.x > this.x)
  1159. this.x = other.x;
  1160. if (other.y > this.y)
  1161. this.y = other.y;
  1162. if (other.z > this.z)
  1163. this.z = other.z;
  1164. if (other.w > this.w)
  1165. this.w = other.w;
  1166. return this;
  1167. };
  1168. // Properties
  1169. Vector4.prototype.length = function () {
  1170. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1171. };
  1172. Vector4.prototype.lengthSquared = function () {
  1173. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1174. };
  1175. // Methods
  1176. Vector4.prototype.normalize = function () {
  1177. var len = this.length();
  1178. if (len === 0)
  1179. return this;
  1180. var num = 1.0 / len;
  1181. this.x *= num;
  1182. this.y *= num;
  1183. this.z *= num;
  1184. this.w *= num;
  1185. return this;
  1186. };
  1187. Vector4.prototype.toVector3 = function () {
  1188. return new Vector3(this.x, this.y, this.z);
  1189. };
  1190. Vector4.prototype.clone = function () {
  1191. return new Vector4(this.x, this.y, this.z, this.w);
  1192. };
  1193. Vector4.prototype.copyFrom = function (source) {
  1194. this.x = source.x;
  1195. this.y = source.y;
  1196. this.z = source.z;
  1197. this.w = source.w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1201. this.x = x;
  1202. this.y = y;
  1203. this.z = z;
  1204. this.w = w;
  1205. return this;
  1206. };
  1207. // Statics
  1208. Vector4.FromArray = function (array, offset) {
  1209. if (!offset) {
  1210. offset = 0;
  1211. }
  1212. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1213. };
  1214. Vector4.FromArrayToRef = function (array, offset, result) {
  1215. result.x = array[offset];
  1216. result.y = array[offset + 1];
  1217. result.z = array[offset + 2];
  1218. result.w = array[offset + 3];
  1219. };
  1220. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1221. result.x = array[offset];
  1222. result.y = array[offset + 1];
  1223. result.z = array[offset + 2];
  1224. result.w = array[offset + 3];
  1225. };
  1226. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1227. result.x = x;
  1228. result.y = y;
  1229. result.z = z;
  1230. result.w = w;
  1231. };
  1232. Vector4.Zero = function () {
  1233. return new Vector4(0, 0, 0, 0);
  1234. };
  1235. Vector4.Normalize = function (vector) {
  1236. var result = Vector4.Zero();
  1237. Vector4.NormalizeToRef(vector, result);
  1238. return result;
  1239. };
  1240. Vector4.NormalizeToRef = function (vector, result) {
  1241. result.copyFrom(vector);
  1242. result.normalize();
  1243. };
  1244. Vector4.Minimize = function (left, right) {
  1245. var min = left.clone();
  1246. min.MinimizeInPlace(right);
  1247. return min;
  1248. };
  1249. Vector4.Maximize = function (left, right) {
  1250. var max = left.clone();
  1251. max.MaximizeInPlace(right);
  1252. return max;
  1253. };
  1254. Vector4.Distance = function (value1, value2) {
  1255. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1256. };
  1257. Vector4.DistanceSquared = function (value1, value2) {
  1258. var x = value1.x - value2.x;
  1259. var y = value1.y - value2.y;
  1260. var z = value1.z - value2.z;
  1261. var w = value1.w - value2.w;
  1262. return (x * x) + (y * y) + (z * z) + (w * w);
  1263. };
  1264. Vector4.Center = function (value1, value2) {
  1265. var center = value1.add(value2);
  1266. center.scaleInPlace(0.5);
  1267. return center;
  1268. };
  1269. return Vector4;
  1270. })();
  1271. BABYLON.Vector4 = Vector4;
  1272. var Quaternion = (function () {
  1273. function Quaternion(x, y, z, w) {
  1274. if (x === void 0) { x = 0; }
  1275. if (y === void 0) { y = 0; }
  1276. if (z === void 0) { z = 0; }
  1277. if (w === void 0) { w = 1; }
  1278. this.x = x;
  1279. this.y = y;
  1280. this.z = z;
  1281. this.w = w;
  1282. }
  1283. Quaternion.prototype.toString = function () {
  1284. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1285. };
  1286. Quaternion.prototype.asArray = function () {
  1287. return [this.x, this.y, this.z, this.w];
  1288. };
  1289. Quaternion.prototype.equals = function (otherQuaternion) {
  1290. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1291. };
  1292. Quaternion.prototype.clone = function () {
  1293. return new Quaternion(this.x, this.y, this.z, this.w);
  1294. };
  1295. Quaternion.prototype.copyFrom = function (other) {
  1296. this.x = other.x;
  1297. this.y = other.y;
  1298. this.z = other.z;
  1299. this.w = other.w;
  1300. return this;
  1301. };
  1302. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1303. this.x = x;
  1304. this.y = y;
  1305. this.z = z;
  1306. this.w = w;
  1307. return this;
  1308. };
  1309. Quaternion.prototype.add = function (other) {
  1310. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1311. };
  1312. Quaternion.prototype.subtract = function (other) {
  1313. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1314. };
  1315. Quaternion.prototype.scale = function (value) {
  1316. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1317. };
  1318. Quaternion.prototype.multiply = function (q1) {
  1319. var result = new Quaternion(0, 0, 0, 1.0);
  1320. this.multiplyToRef(q1, result);
  1321. return result;
  1322. };
  1323. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1324. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1325. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1326. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1327. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1328. result.copyFromFloats(x, y, z, w);
  1329. return this;
  1330. };
  1331. Quaternion.prototype.multiplyInPlace = function (q1) {
  1332. this.multiplyToRef(q1, this);
  1333. return this;
  1334. };
  1335. Quaternion.prototype.conjugateToRef = function (ref) {
  1336. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1337. return this;
  1338. };
  1339. Quaternion.prototype.conjugateInPlace = function () {
  1340. this.x *= -1;
  1341. this.y *= -1;
  1342. this.z *= -1;
  1343. return this;
  1344. };
  1345. Quaternion.prototype.conjugate = function () {
  1346. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1347. return result;
  1348. };
  1349. Quaternion.prototype.length = function () {
  1350. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1351. };
  1352. Quaternion.prototype.normalize = function () {
  1353. var length = 1.0 / this.length();
  1354. this.x *= length;
  1355. this.y *= length;
  1356. this.z *= length;
  1357. this.w *= length;
  1358. return this;
  1359. };
  1360. Quaternion.prototype.toEulerAngles = function (order) {
  1361. if (order === void 0) { order = "YZX"; }
  1362. var result = Vector3.Zero();
  1363. this.toEulerAnglesToRef(result, order);
  1364. return result;
  1365. };
  1366. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1367. if (order === void 0) { order = "YZX"; }
  1368. var heading, attitude, bank;
  1369. var x = this.x, y = this.y, z = this.z, w = this.w;
  1370. switch (order) {
  1371. case "YZX":
  1372. var test = x * y + z * w;
  1373. if (test > 0.499) {
  1374. heading = 2 * Math.atan2(x, w);
  1375. attitude = Math.PI / 2;
  1376. bank = 0;
  1377. }
  1378. if (test < -0.499) {
  1379. heading = -2 * Math.atan2(x, w);
  1380. attitude = -Math.PI / 2;
  1381. bank = 0;
  1382. }
  1383. if (isNaN(heading)) {
  1384. var sqx = x * x;
  1385. var sqy = y * y;
  1386. var sqz = z * z;
  1387. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1388. attitude = Math.asin(2 * test); // attitude
  1389. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1390. }
  1391. break;
  1392. default:
  1393. throw new Error("Euler order " + order + " not supported yet.");
  1394. }
  1395. result.y = heading;
  1396. result.z = attitude;
  1397. result.x = bank;
  1398. return this;
  1399. };
  1400. ;
  1401. Quaternion.prototype.toRotationMatrix = function (result) {
  1402. var xx = this.x * this.x;
  1403. var yy = this.y * this.y;
  1404. var zz = this.z * this.z;
  1405. var xy = this.x * this.y;
  1406. var zw = this.z * this.w;
  1407. var zx = this.z * this.x;
  1408. var yw = this.y * this.w;
  1409. var yz = this.y * this.z;
  1410. var xw = this.x * this.w;
  1411. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1412. result.m[1] = 2.0 * (xy + zw);
  1413. result.m[2] = 2.0 * (zx - yw);
  1414. result.m[3] = 0;
  1415. result.m[4] = 2.0 * (xy - zw);
  1416. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1417. result.m[6] = 2.0 * (yz + xw);
  1418. result.m[7] = 0;
  1419. result.m[8] = 2.0 * (zx + yw);
  1420. result.m[9] = 2.0 * (yz - xw);
  1421. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1422. result.m[11] = 0;
  1423. result.m[12] = 0;
  1424. result.m[13] = 0;
  1425. result.m[14] = 0;
  1426. result.m[15] = 1.0;
  1427. return this;
  1428. };
  1429. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1430. Quaternion.FromRotationMatrixToRef(matrix, this);
  1431. return this;
  1432. };
  1433. // Statics
  1434. Quaternion.FromRotationMatrix = function (matrix) {
  1435. var result = new Quaternion();
  1436. Quaternion.FromRotationMatrixToRef(matrix, result);
  1437. return result;
  1438. };
  1439. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1440. var data = matrix.m;
  1441. var m11 = data[0], m12 = data[4], m13 = data[8];
  1442. var m21 = data[1], m22 = data[5], m23 = data[9];
  1443. var m31 = data[2], m32 = data[6], m33 = data[10];
  1444. var trace = m11 + m22 + m33;
  1445. var s;
  1446. if (trace > 0) {
  1447. s = 0.5 / Math.sqrt(trace + 1.0);
  1448. result.w = 0.25 / s;
  1449. result.x = (m32 - m23) * s;
  1450. result.y = (m13 - m31) * s;
  1451. result.z = (m21 - m12) * s;
  1452. }
  1453. else if (m11 > m22 && m11 > m33) {
  1454. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1455. result.w = (m32 - m23) / s;
  1456. result.x = 0.25 * s;
  1457. result.y = (m12 + m21) / s;
  1458. result.z = (m13 + m31) / s;
  1459. }
  1460. else if (m22 > m33) {
  1461. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1462. result.w = (m13 - m31) / s;
  1463. result.x = (m12 + m21) / s;
  1464. result.y = 0.25 * s;
  1465. result.z = (m23 + m32) / s;
  1466. }
  1467. else {
  1468. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1469. result.w = (m21 - m12) / s;
  1470. result.x = (m13 + m31) / s;
  1471. result.y = (m23 + m32) / s;
  1472. result.z = 0.25 * s;
  1473. }
  1474. };
  1475. Quaternion.Inverse = function (q) {
  1476. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1477. };
  1478. Quaternion.Identity = function () {
  1479. return new Quaternion(0, 0, 0, 1);
  1480. };
  1481. Quaternion.RotationAxis = function (axis, angle) {
  1482. var result = new Quaternion();
  1483. var sin = Math.sin(angle / 2);
  1484. axis.normalize();
  1485. result.w = Math.cos(angle / 2);
  1486. result.x = axis.x * sin;
  1487. result.y = axis.y * sin;
  1488. result.z = axis.z * sin;
  1489. return result;
  1490. };
  1491. Quaternion.FromArray = function (array, offset) {
  1492. if (!offset) {
  1493. offset = 0;
  1494. }
  1495. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1496. };
  1497. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1498. var result = new Quaternion();
  1499. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1500. return result;
  1501. };
  1502. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1503. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1504. var halfRoll = roll * 0.5;
  1505. var halfPitch = pitch * 0.5;
  1506. var halfYaw = yaw * 0.5;
  1507. var sinRoll = Math.sin(halfRoll);
  1508. var cosRoll = Math.cos(halfRoll);
  1509. var sinPitch = Math.sin(halfPitch);
  1510. var cosPitch = Math.cos(halfPitch);
  1511. var sinYaw = Math.sin(halfYaw);
  1512. var cosYaw = Math.cos(halfYaw);
  1513. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1514. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1515. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1516. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1517. };
  1518. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1519. var result = new Quaternion();
  1520. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1521. return result;
  1522. };
  1523. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1524. // Produces a quaternion from Euler angles in the z-x-z orientation
  1525. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1526. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1527. var halfBeta = beta * 0.5;
  1528. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1529. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1530. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1531. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1532. };
  1533. Quaternion.Slerp = function (left, right, amount) {
  1534. var num2;
  1535. var num3;
  1536. var num = amount;
  1537. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1538. var flag = false;
  1539. if (num4 < 0) {
  1540. flag = true;
  1541. num4 = -num4;
  1542. }
  1543. if (num4 > 0.999999) {
  1544. num3 = 1 - num;
  1545. num2 = flag ? -num : num;
  1546. }
  1547. else {
  1548. var num5 = Math.acos(num4);
  1549. var num6 = (1.0 / Math.sin(num5));
  1550. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1551. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1552. }
  1553. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1554. };
  1555. return Quaternion;
  1556. })();
  1557. BABYLON.Quaternion = Quaternion;
  1558. var Matrix = (function () {
  1559. function Matrix() {
  1560. this.m = new Float32Array(16);
  1561. }
  1562. // Properties
  1563. Matrix.prototype.isIdentity = function () {
  1564. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1565. return false;
  1566. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1567. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1568. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1569. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1570. return false;
  1571. return true;
  1572. };
  1573. Matrix.prototype.determinant = function () {
  1574. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1575. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1576. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1577. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1578. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1579. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1580. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1581. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1582. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1583. };
  1584. // Methods
  1585. Matrix.prototype.toArray = function () {
  1586. return this.m;
  1587. };
  1588. Matrix.prototype.asArray = function () {
  1589. return this.toArray();
  1590. };
  1591. Matrix.prototype.invert = function () {
  1592. this.invertToRef(this);
  1593. return this;
  1594. };
  1595. Matrix.prototype.reset = function () {
  1596. for (var index = 0; index < 16; index++) {
  1597. this.m[index] = 0;
  1598. }
  1599. return this;
  1600. };
  1601. Matrix.prototype.add = function (other) {
  1602. var result = new Matrix();
  1603. this.addToRef(other, result);
  1604. return result;
  1605. };
  1606. Matrix.prototype.addToRef = function (other, result) {
  1607. for (var index = 0; index < 16; index++) {
  1608. result.m[index] = this.m[index] + other.m[index];
  1609. }
  1610. return this;
  1611. };
  1612. Matrix.prototype.addToSelf = function (other) {
  1613. for (var index = 0; index < 16; index++) {
  1614. this.m[index] += other.m[index];
  1615. }
  1616. return this;
  1617. };
  1618. Matrix.prototype.invertToRef = function (other) {
  1619. var l1 = this.m[0];
  1620. var l2 = this.m[1];
  1621. var l3 = this.m[2];
  1622. var l4 = this.m[3];
  1623. var l5 = this.m[4];
  1624. var l6 = this.m[5];
  1625. var l7 = this.m[6];
  1626. var l8 = this.m[7];
  1627. var l9 = this.m[8];
  1628. var l10 = this.m[9];
  1629. var l11 = this.m[10];
  1630. var l12 = this.m[11];
  1631. var l13 = this.m[12];
  1632. var l14 = this.m[13];
  1633. var l15 = this.m[14];
  1634. var l16 = this.m[15];
  1635. var l17 = (l11 * l16) - (l12 * l15);
  1636. var l18 = (l10 * l16) - (l12 * l14);
  1637. var l19 = (l10 * l15) - (l11 * l14);
  1638. var l20 = (l9 * l16) - (l12 * l13);
  1639. var l21 = (l9 * l15) - (l11 * l13);
  1640. var l22 = (l9 * l14) - (l10 * l13);
  1641. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1642. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1643. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1644. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1645. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1646. var l28 = (l7 * l16) - (l8 * l15);
  1647. var l29 = (l6 * l16) - (l8 * l14);
  1648. var l30 = (l6 * l15) - (l7 * l14);
  1649. var l31 = (l5 * l16) - (l8 * l13);
  1650. var l32 = (l5 * l15) - (l7 * l13);
  1651. var l33 = (l5 * l14) - (l6 * l13);
  1652. var l34 = (l7 * l12) - (l8 * l11);
  1653. var l35 = (l6 * l12) - (l8 * l10);
  1654. var l36 = (l6 * l11) - (l7 * l10);
  1655. var l37 = (l5 * l12) - (l8 * l9);
  1656. var l38 = (l5 * l11) - (l7 * l9);
  1657. var l39 = (l5 * l10) - (l6 * l9);
  1658. other.m[0] = l23 * l27;
  1659. other.m[4] = l24 * l27;
  1660. other.m[8] = l25 * l27;
  1661. other.m[12] = l26 * l27;
  1662. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1663. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1664. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1665. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1666. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1667. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1668. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1669. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1670. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1671. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1672. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1673. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1674. return this;
  1675. };
  1676. Matrix.prototype.setTranslation = function (vector3) {
  1677. this.m[12] = vector3.x;
  1678. this.m[13] = vector3.y;
  1679. this.m[14] = vector3.z;
  1680. return this;
  1681. };
  1682. Matrix.prototype.getTranslation = function () {
  1683. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1684. };
  1685. Matrix.prototype.multiply = function (other) {
  1686. var result = new Matrix();
  1687. this.multiplyToRef(other, result);
  1688. return result;
  1689. };
  1690. Matrix.prototype.copyFrom = function (other) {
  1691. for (var index = 0; index < 16; index++) {
  1692. this.m[index] = other.m[index];
  1693. }
  1694. return this;
  1695. };
  1696. Matrix.prototype.copyToArray = function (array, offset) {
  1697. if (offset === void 0) { offset = 0; }
  1698. for (var index = 0; index < 16; index++) {
  1699. array[offset + index] = this.m[index];
  1700. }
  1701. return this;
  1702. };
  1703. Matrix.prototype.multiplyToRef = function (other, result) {
  1704. this.multiplyToArray(other, result.m, 0);
  1705. return this;
  1706. };
  1707. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1708. var tm0 = this.m[0];
  1709. var tm1 = this.m[1];
  1710. var tm2 = this.m[2];
  1711. var tm3 = this.m[3];
  1712. var tm4 = this.m[4];
  1713. var tm5 = this.m[5];
  1714. var tm6 = this.m[6];
  1715. var tm7 = this.m[7];
  1716. var tm8 = this.m[8];
  1717. var tm9 = this.m[9];
  1718. var tm10 = this.m[10];
  1719. var tm11 = this.m[11];
  1720. var tm12 = this.m[12];
  1721. var tm13 = this.m[13];
  1722. var tm14 = this.m[14];
  1723. var tm15 = this.m[15];
  1724. var om0 = other.m[0];
  1725. var om1 = other.m[1];
  1726. var om2 = other.m[2];
  1727. var om3 = other.m[3];
  1728. var om4 = other.m[4];
  1729. var om5 = other.m[5];
  1730. var om6 = other.m[6];
  1731. var om7 = other.m[7];
  1732. var om8 = other.m[8];
  1733. var om9 = other.m[9];
  1734. var om10 = other.m[10];
  1735. var om11 = other.m[11];
  1736. var om12 = other.m[12];
  1737. var om13 = other.m[13];
  1738. var om14 = other.m[14];
  1739. var om15 = other.m[15];
  1740. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1741. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1742. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1743. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1744. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1745. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1746. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1747. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1748. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1749. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1750. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1751. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1752. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1753. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1754. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1755. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1756. return this;
  1757. };
  1758. Matrix.prototype.equals = function (value) {
  1759. return value &&
  1760. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1761. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1762. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1763. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1764. };
  1765. Matrix.prototype.clone = function () {
  1766. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1767. };
  1768. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1769. translation.x = this.m[12];
  1770. translation.y = this.m[13];
  1771. translation.z = this.m[14];
  1772. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1773. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1774. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1775. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1776. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1777. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1778. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1779. rotation.x = 0;
  1780. rotation.y = 0;
  1781. rotation.z = 0;
  1782. rotation.w = 1;
  1783. return false;
  1784. }
  1785. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1786. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1787. return true;
  1788. };
  1789. // Statics
  1790. Matrix.FromArray = function (array, offset) {
  1791. var result = new Matrix();
  1792. if (!offset) {
  1793. offset = 0;
  1794. }
  1795. Matrix.FromArrayToRef(array, offset, result);
  1796. return result;
  1797. };
  1798. Matrix.FromArrayToRef = function (array, offset, result) {
  1799. for (var index = 0; index < 16; index++) {
  1800. result.m[index] = array[index + offset];
  1801. }
  1802. };
  1803. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1804. for (var index = 0; index < 16; index++) {
  1805. result.m[index] = array[index + offset] * scale;
  1806. }
  1807. };
  1808. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1809. result.m[0] = initialM11;
  1810. result.m[1] = initialM12;
  1811. result.m[2] = initialM13;
  1812. result.m[3] = initialM14;
  1813. result.m[4] = initialM21;
  1814. result.m[5] = initialM22;
  1815. result.m[6] = initialM23;
  1816. result.m[7] = initialM24;
  1817. result.m[8] = initialM31;
  1818. result.m[9] = initialM32;
  1819. result.m[10] = initialM33;
  1820. result.m[11] = initialM34;
  1821. result.m[12] = initialM41;
  1822. result.m[13] = initialM42;
  1823. result.m[14] = initialM43;
  1824. result.m[15] = initialM44;
  1825. };
  1826. Matrix.prototype.getRow = function (index) {
  1827. if (index < 0 || index > 3) {
  1828. return null;
  1829. }
  1830. var i = index * 4;
  1831. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  1832. };
  1833. Matrix.prototype.setRow = function (index, row) {
  1834. if (index < 0 || index > 3) {
  1835. return this;
  1836. }
  1837. var i = index * 4;
  1838. this.m[i + 0] = row.x;
  1839. this.m[i + 1] = row.y;
  1840. this.m[i + 2] = row.z;
  1841. this.m[i + 3] = row.w;
  1842. return this;
  1843. };
  1844. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1845. var result = new Matrix();
  1846. result.m[0] = initialM11;
  1847. result.m[1] = initialM12;
  1848. result.m[2] = initialM13;
  1849. result.m[3] = initialM14;
  1850. result.m[4] = initialM21;
  1851. result.m[5] = initialM22;
  1852. result.m[6] = initialM23;
  1853. result.m[7] = initialM24;
  1854. result.m[8] = initialM31;
  1855. result.m[9] = initialM32;
  1856. result.m[10] = initialM33;
  1857. result.m[11] = initialM34;
  1858. result.m[12] = initialM41;
  1859. result.m[13] = initialM42;
  1860. result.m[14] = initialM43;
  1861. result.m[15] = initialM44;
  1862. return result;
  1863. };
  1864. Matrix.Compose = function (scale, rotation, translation) {
  1865. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1866. var rotationMatrix = Matrix.Identity();
  1867. rotation.toRotationMatrix(rotationMatrix);
  1868. result = result.multiply(rotationMatrix);
  1869. result.setTranslation(translation);
  1870. return result;
  1871. };
  1872. Matrix.Identity = function () {
  1873. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1874. };
  1875. Matrix.IdentityToRef = function (result) {
  1876. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1877. };
  1878. Matrix.Zero = function () {
  1879. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1880. };
  1881. Matrix.RotationX = function (angle) {
  1882. var result = new Matrix();
  1883. Matrix.RotationXToRef(angle, result);
  1884. return result;
  1885. };
  1886. Matrix.Invert = function (source) {
  1887. var result = new Matrix();
  1888. source.invertToRef(result);
  1889. return result;
  1890. };
  1891. Matrix.RotationXToRef = function (angle, result) {
  1892. var s = Math.sin(angle);
  1893. var c = Math.cos(angle);
  1894. result.m[0] = 1.0;
  1895. result.m[15] = 1.0;
  1896. result.m[5] = c;
  1897. result.m[10] = c;
  1898. result.m[9] = -s;
  1899. result.m[6] = s;
  1900. result.m[1] = 0;
  1901. result.m[2] = 0;
  1902. result.m[3] = 0;
  1903. result.m[4] = 0;
  1904. result.m[7] = 0;
  1905. result.m[8] = 0;
  1906. result.m[11] = 0;
  1907. result.m[12] = 0;
  1908. result.m[13] = 0;
  1909. result.m[14] = 0;
  1910. };
  1911. Matrix.RotationY = function (angle) {
  1912. var result = new Matrix();
  1913. Matrix.RotationYToRef(angle, result);
  1914. return result;
  1915. };
  1916. Matrix.RotationYToRef = function (angle, result) {
  1917. var s = Math.sin(angle);
  1918. var c = Math.cos(angle);
  1919. result.m[5] = 1.0;
  1920. result.m[15] = 1.0;
  1921. result.m[0] = c;
  1922. result.m[2] = -s;
  1923. result.m[8] = s;
  1924. result.m[10] = c;
  1925. result.m[1] = 0;
  1926. result.m[3] = 0;
  1927. result.m[4] = 0;
  1928. result.m[6] = 0;
  1929. result.m[7] = 0;
  1930. result.m[9] = 0;
  1931. result.m[11] = 0;
  1932. result.m[12] = 0;
  1933. result.m[13] = 0;
  1934. result.m[14] = 0;
  1935. };
  1936. Matrix.RotationZ = function (angle) {
  1937. var result = new Matrix();
  1938. Matrix.RotationZToRef(angle, result);
  1939. return result;
  1940. };
  1941. Matrix.RotationZToRef = function (angle, result) {
  1942. var s = Math.sin(angle);
  1943. var c = Math.cos(angle);
  1944. result.m[10] = 1.0;
  1945. result.m[15] = 1.0;
  1946. result.m[0] = c;
  1947. result.m[1] = s;
  1948. result.m[4] = -s;
  1949. result.m[5] = c;
  1950. result.m[2] = 0;
  1951. result.m[3] = 0;
  1952. result.m[6] = 0;
  1953. result.m[7] = 0;
  1954. result.m[8] = 0;
  1955. result.m[9] = 0;
  1956. result.m[11] = 0;
  1957. result.m[12] = 0;
  1958. result.m[13] = 0;
  1959. result.m[14] = 0;
  1960. };
  1961. Matrix.RotationAxis = function (axis, angle) {
  1962. var result = Matrix.Zero();
  1963. Matrix.RotationAxisToRef(axis, angle, result);
  1964. return result;
  1965. };
  1966. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1967. var s = Math.sin(-angle);
  1968. var c = Math.cos(-angle);
  1969. var c1 = 1 - c;
  1970. axis.normalize();
  1971. result.m[0] = (axis.x * axis.x) * c1 + c;
  1972. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1973. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1974. result.m[3] = 0.0;
  1975. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1976. result.m[5] = (axis.y * axis.y) * c1 + c;
  1977. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1978. result.m[7] = 0.0;
  1979. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1980. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1981. result.m[10] = (axis.z * axis.z) * c1 + c;
  1982. result.m[11] = 0.0;
  1983. result.m[15] = 1.0;
  1984. };
  1985. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1986. var result = new Matrix();
  1987. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1988. return result;
  1989. };
  1990. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1991. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1992. this._tempQuaternion.toRotationMatrix(result);
  1993. };
  1994. Matrix.Scaling = function (x, y, z) {
  1995. var result = Matrix.Zero();
  1996. Matrix.ScalingToRef(x, y, z, result);
  1997. return result;
  1998. };
  1999. Matrix.ScalingToRef = function (x, y, z, result) {
  2000. result.m[0] = x;
  2001. result.m[1] = 0;
  2002. result.m[2] = 0;
  2003. result.m[3] = 0;
  2004. result.m[4] = 0;
  2005. result.m[5] = y;
  2006. result.m[6] = 0;
  2007. result.m[7] = 0;
  2008. result.m[8] = 0;
  2009. result.m[9] = 0;
  2010. result.m[10] = z;
  2011. result.m[11] = 0;
  2012. result.m[12] = 0;
  2013. result.m[13] = 0;
  2014. result.m[14] = 0;
  2015. result.m[15] = 1.0;
  2016. };
  2017. Matrix.Translation = function (x, y, z) {
  2018. var result = Matrix.Identity();
  2019. Matrix.TranslationToRef(x, y, z, result);
  2020. return result;
  2021. };
  2022. Matrix.TranslationToRef = function (x, y, z, result) {
  2023. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2024. };
  2025. Matrix.Lerp = function (startValue, endValue, gradient) {
  2026. var startScale = new Vector3(0, 0, 0);
  2027. var startRotation = new Quaternion();
  2028. var startTranslation = new Vector3(0, 0, 0);
  2029. startValue.decompose(startScale, startRotation, startTranslation);
  2030. var endScale = new Vector3(0, 0, 0);
  2031. var endRotation = new Quaternion();
  2032. var endTranslation = new Vector3(0, 0, 0);
  2033. endValue.decompose(endScale, endRotation, endTranslation);
  2034. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2035. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2036. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2037. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2038. };
  2039. Matrix.LookAtLH = function (eye, target, up) {
  2040. var result = Matrix.Zero();
  2041. Matrix.LookAtLHToRef(eye, target, up, result);
  2042. return result;
  2043. };
  2044. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2045. // Z axis
  2046. target.subtractToRef(eye, this._zAxis);
  2047. this._zAxis.normalize();
  2048. // X axis
  2049. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2050. if (this._xAxis.lengthSquared() === 0) {
  2051. this._xAxis.x = 1.0;
  2052. }
  2053. else {
  2054. this._xAxis.normalize();
  2055. }
  2056. // Y axis
  2057. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2058. this._yAxis.normalize();
  2059. // Eye angles
  2060. var ex = -Vector3.Dot(this._xAxis, eye);
  2061. var ey = -Vector3.Dot(this._yAxis, eye);
  2062. var ez = -Vector3.Dot(this._zAxis, eye);
  2063. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2064. };
  2065. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2066. var matrix = Matrix.Zero();
  2067. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2068. return matrix;
  2069. };
  2070. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2071. var hw = 2.0 / width;
  2072. var hh = 2.0 / height;
  2073. var id = 1.0 / (zfar - znear);
  2074. var nid = znear / (znear - zfar);
  2075. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2076. };
  2077. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2078. var matrix = Matrix.Zero();
  2079. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2080. return matrix;
  2081. };
  2082. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2083. result.m[0] = 2.0 / (right - left);
  2084. result.m[1] = result.m[2] = result.m[3] = 0;
  2085. result.m[5] = 2.0 / (top - bottom);
  2086. result.m[4] = result.m[6] = result.m[7] = 0;
  2087. result.m[10] = -1.0 / (znear - zfar);
  2088. result.m[8] = result.m[9] = result.m[11] = 0;
  2089. result.m[12] = (left + right) / (left - right);
  2090. result.m[13] = (top + bottom) / (bottom - top);
  2091. result.m[14] = znear / (znear - zfar);
  2092. result.m[15] = 1.0;
  2093. };
  2094. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2095. var matrix = Matrix.Zero();
  2096. matrix.m[0] = (2.0 * znear) / width;
  2097. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2098. matrix.m[5] = (2.0 * znear) / height;
  2099. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2100. matrix.m[10] = -zfar / (znear - zfar);
  2101. matrix.m[8] = matrix.m[9] = 0.0;
  2102. matrix.m[11] = 1.0;
  2103. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2104. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2105. return matrix;
  2106. };
  2107. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2108. var matrix = Matrix.Zero();
  2109. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2110. return matrix;
  2111. };
  2112. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2113. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2114. var tan = 1.0 / (Math.tan(fov * 0.5));
  2115. if (isVerticalFovFixed) {
  2116. result.m[0] = tan / aspect;
  2117. }
  2118. else {
  2119. result.m[0] = tan;
  2120. }
  2121. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2122. if (isVerticalFovFixed) {
  2123. result.m[5] = tan;
  2124. }
  2125. else {
  2126. result.m[5] = tan * aspect;
  2127. }
  2128. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2129. result.m[8] = result.m[9] = 0.0;
  2130. result.m[10] = -zfar / (znear - zfar);
  2131. result.m[11] = 1.0;
  2132. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2133. result.m[14] = (znear * zfar) / (znear - zfar);
  2134. };
  2135. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2136. var cw = viewport.width;
  2137. var ch = viewport.height;
  2138. var cx = viewport.x;
  2139. var cy = viewport.y;
  2140. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2141. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2142. };
  2143. Matrix.GetAsMatrix2x2 = function (matrix) {
  2144. return new Float32Array([
  2145. matrix.m[0], matrix.m[1],
  2146. matrix.m[4], matrix.m[5]
  2147. ]);
  2148. };
  2149. Matrix.GetAsMatrix3x3 = function (matrix) {
  2150. return new Float32Array([
  2151. matrix.m[0], matrix.m[1], matrix.m[2],
  2152. matrix.m[4], matrix.m[5], matrix.m[6],
  2153. matrix.m[8], matrix.m[9], matrix.m[10]
  2154. ]);
  2155. };
  2156. Matrix.Transpose = function (matrix) {
  2157. var result = new Matrix();
  2158. result.m[0] = matrix.m[0];
  2159. result.m[1] = matrix.m[4];
  2160. result.m[2] = matrix.m[8];
  2161. result.m[3] = matrix.m[12];
  2162. result.m[4] = matrix.m[1];
  2163. result.m[5] = matrix.m[5];
  2164. result.m[6] = matrix.m[9];
  2165. result.m[7] = matrix.m[13];
  2166. result.m[8] = matrix.m[2];
  2167. result.m[9] = matrix.m[6];
  2168. result.m[10] = matrix.m[10];
  2169. result.m[11] = matrix.m[14];
  2170. result.m[12] = matrix.m[3];
  2171. result.m[13] = matrix.m[7];
  2172. result.m[14] = matrix.m[11];
  2173. result.m[15] = matrix.m[15];
  2174. return result;
  2175. };
  2176. Matrix.Reflection = function (plane) {
  2177. var matrix = new Matrix();
  2178. Matrix.ReflectionToRef(plane, matrix);
  2179. return matrix;
  2180. };
  2181. Matrix.ReflectionToRef = function (plane, result) {
  2182. plane.normalize();
  2183. var x = plane.normal.x;
  2184. var y = plane.normal.y;
  2185. var z = plane.normal.z;
  2186. var temp = -2 * x;
  2187. var temp2 = -2 * y;
  2188. var temp3 = -2 * z;
  2189. result.m[0] = (temp * x) + 1;
  2190. result.m[1] = temp2 * x;
  2191. result.m[2] = temp3 * x;
  2192. result.m[3] = 0.0;
  2193. result.m[4] = temp * y;
  2194. result.m[5] = (temp2 * y) + 1;
  2195. result.m[6] = temp3 * y;
  2196. result.m[7] = 0.0;
  2197. result.m[8] = temp * z;
  2198. result.m[9] = temp2 * z;
  2199. result.m[10] = (temp3 * z) + 1;
  2200. result.m[11] = 0.0;
  2201. result.m[12] = temp * plane.d;
  2202. result.m[13] = temp2 * plane.d;
  2203. result.m[14] = temp3 * plane.d;
  2204. result.m[15] = 1.0;
  2205. };
  2206. Matrix._tempQuaternion = new Quaternion();
  2207. Matrix._xAxis = Vector3.Zero();
  2208. Matrix._yAxis = Vector3.Zero();
  2209. Matrix._zAxis = Vector3.Zero();
  2210. return Matrix;
  2211. })();
  2212. BABYLON.Matrix = Matrix;
  2213. var Plane = (function () {
  2214. function Plane(a, b, c, d) {
  2215. this.normal = new Vector3(a, b, c);
  2216. this.d = d;
  2217. }
  2218. Plane.prototype.asArray = function () {
  2219. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2220. };
  2221. // Methods
  2222. Plane.prototype.clone = function () {
  2223. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2224. };
  2225. Plane.prototype.normalize = function () {
  2226. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2227. var magnitude = 0;
  2228. if (norm !== 0) {
  2229. magnitude = 1.0 / norm;
  2230. }
  2231. this.normal.x *= magnitude;
  2232. this.normal.y *= magnitude;
  2233. this.normal.z *= magnitude;
  2234. this.d *= magnitude;
  2235. return this;
  2236. };
  2237. Plane.prototype.transform = function (transformation) {
  2238. var transposedMatrix = Matrix.Transpose(transformation);
  2239. var x = this.normal.x;
  2240. var y = this.normal.y;
  2241. var z = this.normal.z;
  2242. var d = this.d;
  2243. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2244. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2245. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2246. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2247. return new Plane(normalX, normalY, normalZ, finalD);
  2248. };
  2249. Plane.prototype.dotCoordinate = function (point) {
  2250. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2251. };
  2252. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2253. var x1 = point2.x - point1.x;
  2254. var y1 = point2.y - point1.y;
  2255. var z1 = point2.z - point1.z;
  2256. var x2 = point3.x - point1.x;
  2257. var y2 = point3.y - point1.y;
  2258. var z2 = point3.z - point1.z;
  2259. var yz = (y1 * z2) - (z1 * y2);
  2260. var xz = (z1 * x2) - (x1 * z2);
  2261. var xy = (x1 * y2) - (y1 * x2);
  2262. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2263. var invPyth;
  2264. if (pyth !== 0) {
  2265. invPyth = 1.0 / pyth;
  2266. }
  2267. else {
  2268. invPyth = 0;
  2269. }
  2270. this.normal.x = yz * invPyth;
  2271. this.normal.y = xz * invPyth;
  2272. this.normal.z = xy * invPyth;
  2273. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2274. return this;
  2275. };
  2276. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2277. var dot = Vector3.Dot(this.normal, direction);
  2278. return (dot <= epsilon);
  2279. };
  2280. Plane.prototype.signedDistanceTo = function (point) {
  2281. return Vector3.Dot(point, this.normal) + this.d;
  2282. };
  2283. // Statics
  2284. Plane.FromArray = function (array) {
  2285. return new Plane(array[0], array[1], array[2], array[3]);
  2286. };
  2287. Plane.FromPoints = function (point1, point2, point3) {
  2288. var result = new Plane(0, 0, 0, 0);
  2289. result.copyFromPoints(point1, point2, point3);
  2290. return result;
  2291. };
  2292. Plane.FromPositionAndNormal = function (origin, normal) {
  2293. var result = new Plane(0, 0, 0, 0);
  2294. normal.normalize();
  2295. result.normal = normal;
  2296. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2297. return result;
  2298. };
  2299. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2300. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2301. return Vector3.Dot(point, normal) + d;
  2302. };
  2303. return Plane;
  2304. })();
  2305. BABYLON.Plane = Plane;
  2306. var Viewport = (function () {
  2307. function Viewport(x, y, width, height) {
  2308. this.x = x;
  2309. this.y = y;
  2310. this.width = width;
  2311. this.height = height;
  2312. }
  2313. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2314. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2315. };
  2316. return Viewport;
  2317. })();
  2318. BABYLON.Viewport = Viewport;
  2319. var Frustum = (function () {
  2320. function Frustum() {
  2321. }
  2322. Frustum.GetPlanes = function (transform) {
  2323. var frustumPlanes = [];
  2324. for (var index = 0; index < 6; index++) {
  2325. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2326. }
  2327. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2328. return frustumPlanes;
  2329. };
  2330. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2331. // Near
  2332. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2333. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2334. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2335. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2336. frustumPlanes[0].normalize();
  2337. // Far
  2338. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2339. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2340. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2341. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2342. frustumPlanes[1].normalize();
  2343. // Left
  2344. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2345. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2346. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2347. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2348. frustumPlanes[2].normalize();
  2349. // Right
  2350. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2351. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2352. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2353. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2354. frustumPlanes[3].normalize();
  2355. // Top
  2356. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2357. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2358. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2359. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2360. frustumPlanes[4].normalize();
  2361. // Bottom
  2362. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2363. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2364. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2365. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2366. frustumPlanes[5].normalize();
  2367. };
  2368. return Frustum;
  2369. })();
  2370. BABYLON.Frustum = Frustum;
  2371. (function (Space) {
  2372. Space[Space["LOCAL"] = 0] = "LOCAL";
  2373. Space[Space["WORLD"] = 1] = "WORLD";
  2374. })(BABYLON.Space || (BABYLON.Space = {}));
  2375. var Space = BABYLON.Space;
  2376. var Axis = (function () {
  2377. function Axis() {
  2378. }
  2379. Axis.X = new Vector3(1, 0, 0);
  2380. Axis.Y = new Vector3(0, 1, 0);
  2381. Axis.Z = new Vector3(0, 0, 1);
  2382. return Axis;
  2383. })();
  2384. BABYLON.Axis = Axis;
  2385. ;
  2386. var BezierCurve = (function () {
  2387. function BezierCurve() {
  2388. }
  2389. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2390. // Extract X (which is equal to time here)
  2391. var f0 = 1 - 3 * x2 + 3 * x1;
  2392. var f1 = 3 * x2 - 6 * x1;
  2393. var f2 = 3 * x1;
  2394. var refinedT = t;
  2395. for (var i = 0; i < 5; i++) {
  2396. var refinedT2 = refinedT * refinedT;
  2397. var refinedT3 = refinedT2 * refinedT;
  2398. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2399. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2400. refinedT -= (x - t) * slope;
  2401. refinedT = Math.min(1, Math.max(0, refinedT));
  2402. }
  2403. // Resolve cubic bezier for the given x
  2404. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2405. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2406. Math.pow(refinedT, 3);
  2407. };
  2408. return BezierCurve;
  2409. })();
  2410. BABYLON.BezierCurve = BezierCurve;
  2411. (function (Orientation) {
  2412. Orientation[Orientation["CW"] = 0] = "CW";
  2413. Orientation[Orientation["CCW"] = 1] = "CCW";
  2414. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2415. var Orientation = BABYLON.Orientation;
  2416. var Angle = (function () {
  2417. function Angle(radians) {
  2418. var _this = this;
  2419. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2420. this.radians = function () { return _this._radians; };
  2421. this._radians = radians;
  2422. if (this._radians < 0)
  2423. this._radians += (2 * Math.PI);
  2424. }
  2425. Angle.BetweenTwoPoints = function (a, b) {
  2426. var delta = b.subtract(a);
  2427. var theta = Math.atan2(delta.y, delta.x);
  2428. return new Angle(theta);
  2429. };
  2430. Angle.FromRadians = function (radians) {
  2431. return new Angle(radians);
  2432. };
  2433. Angle.FromDegrees = function (degrees) {
  2434. return new Angle(degrees * Math.PI / 180);
  2435. };
  2436. return Angle;
  2437. })();
  2438. BABYLON.Angle = Angle;
  2439. var Arc2 = (function () {
  2440. function Arc2(startPoint, midPoint, endPoint) {
  2441. this.startPoint = startPoint;
  2442. this.midPoint = midPoint;
  2443. this.endPoint = endPoint;
  2444. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2445. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2446. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2447. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2448. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2449. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2450. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2451. var a1 = this.startAngle.degrees();
  2452. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2453. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2454. // angles correction
  2455. if (a2 - a1 > +180.0)
  2456. a2 -= 360.0;
  2457. if (a2 - a1 < -180.0)
  2458. a2 += 360.0;
  2459. if (a3 - a2 > +180.0)
  2460. a3 -= 360.0;
  2461. if (a3 - a2 < -180.0)
  2462. a3 += 360.0;
  2463. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2464. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2465. }
  2466. return Arc2;
  2467. })();
  2468. BABYLON.Arc2 = Arc2;
  2469. var Path2 = (function () {
  2470. function Path2(x, y) {
  2471. this._points = new Array();
  2472. this._length = 0;
  2473. this.closed = false;
  2474. this._points.push(new Vector2(x, y));
  2475. }
  2476. Path2.prototype.addLineTo = function (x, y) {
  2477. if (closed) {
  2478. //Tools.Error("cannot add lines to closed paths");
  2479. return this;
  2480. }
  2481. var newPoint = new Vector2(x, y);
  2482. var previousPoint = this._points[this._points.length - 1];
  2483. this._points.push(newPoint);
  2484. this._length += newPoint.subtract(previousPoint).length();
  2485. return this;
  2486. };
  2487. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2488. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2489. if (closed) {
  2490. //Tools.Error("cannot add arcs to closed paths");
  2491. return this;
  2492. }
  2493. var startPoint = this._points[this._points.length - 1];
  2494. var midPoint = new Vector2(midX, midY);
  2495. var endPoint = new Vector2(endX, endY);
  2496. var arc = new Arc2(startPoint, midPoint, endPoint);
  2497. var increment = arc.angle.radians() / numberOfSegments;
  2498. if (arc.orientation === Orientation.CW)
  2499. increment *= -1;
  2500. var currentAngle = arc.startAngle.radians() + increment;
  2501. for (var i = 0; i < numberOfSegments; i++) {
  2502. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2503. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2504. this.addLineTo(x, y);
  2505. currentAngle += increment;
  2506. }
  2507. return this;
  2508. };
  2509. Path2.prototype.close = function () {
  2510. this.closed = true;
  2511. return this;
  2512. };
  2513. Path2.prototype.length = function () {
  2514. var result = this._length;
  2515. if (!this.closed) {
  2516. var lastPoint = this._points[this._points.length - 1];
  2517. var firstPoint = this._points[0];
  2518. result += (firstPoint.subtract(lastPoint).length());
  2519. }
  2520. return result;
  2521. };
  2522. Path2.prototype.getPoints = function () {
  2523. return this._points;
  2524. };
  2525. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2526. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2527. //Tools.Error("normalized length position should be between 0 and 1.");
  2528. return Vector2.Zero();
  2529. }
  2530. var lengthPosition = normalizedLengthPosition * this.length();
  2531. var previousOffset = 0;
  2532. for (var i = 0; i < this._points.length; i++) {
  2533. var j = (i + 1) % this._points.length;
  2534. var a = this._points[i];
  2535. var b = this._points[j];
  2536. var bToA = b.subtract(a);
  2537. var nextOffset = (bToA.length() + previousOffset);
  2538. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2539. var dir = bToA.normalize();
  2540. var localOffset = lengthPosition - previousOffset;
  2541. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2542. }
  2543. previousOffset = nextOffset;
  2544. }
  2545. //Tools.Error("internal error");
  2546. return Vector2.Zero();
  2547. };
  2548. Path2.StartingAt = function (x, y) {
  2549. return new Path2(x, y);
  2550. };
  2551. return Path2;
  2552. })();
  2553. BABYLON.Path2 = Path2;
  2554. var Path3D = (function () {
  2555. /**
  2556. * new Path3D(path, normal, raw)
  2557. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2558. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2559. * path : an array of Vector3, the curve axis of the Path3D
  2560. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2561. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2562. */
  2563. function Path3D(path, firstNormal, raw) {
  2564. this.path = path;
  2565. this._curve = new Array();
  2566. this._distances = new Array();
  2567. this._tangents = new Array();
  2568. this._normals = new Array();
  2569. this._binormals = new Array();
  2570. for (var p = 0; p < path.length; p++) {
  2571. this._curve[p] = path[p].clone(); // hard copy
  2572. }
  2573. this._raw = raw || false;
  2574. this._compute(firstNormal);
  2575. }
  2576. /**
  2577. * Returns the Path3D array of successive Vector3 designing its curve.
  2578. */
  2579. Path3D.prototype.getCurve = function () {
  2580. return this._curve;
  2581. };
  2582. /**
  2583. * Returns an array populated with tangent vectors on each Path3D curve point.
  2584. */
  2585. Path3D.prototype.getTangents = function () {
  2586. return this._tangents;
  2587. };
  2588. /**
  2589. * Returns an array populated with normal vectors on each Path3D curve point.
  2590. */
  2591. Path3D.prototype.getNormals = function () {
  2592. return this._normals;
  2593. };
  2594. /**
  2595. * Returns an array populated with binormal vectors on each Path3D curve point.
  2596. */
  2597. Path3D.prototype.getBinormals = function () {
  2598. return this._binormals;
  2599. };
  2600. /**
  2601. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2602. */
  2603. Path3D.prototype.getDistances = function () {
  2604. return this._distances;
  2605. };
  2606. /**
  2607. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2608. * Returns the same object updated.
  2609. */
  2610. Path3D.prototype.update = function (path, firstNormal) {
  2611. for (var p = 0; p < path.length; p++) {
  2612. this._curve[p].x = path[p].x;
  2613. this._curve[p].y = path[p].y;
  2614. this._curve[p].z = path[p].z;
  2615. }
  2616. this._compute(firstNormal);
  2617. return this;
  2618. };
  2619. // private function compute() : computes tangents, normals and binormals
  2620. Path3D.prototype._compute = function (firstNormal) {
  2621. var l = this._curve.length;
  2622. // first and last tangents
  2623. this._tangents[0] = this._getFirstNonNullVector(0);
  2624. if (!this._raw) {
  2625. this._tangents[0].normalize();
  2626. }
  2627. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2628. if (!this._raw) {
  2629. this._tangents[l - 1].normalize();
  2630. }
  2631. // normals and binormals at first point : arbitrary vector with _normalVector()
  2632. var tg0 = this._tangents[0];
  2633. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2634. this._normals[0] = pp0;
  2635. if (!this._raw) {
  2636. this._normals[0].normalize();
  2637. }
  2638. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2639. if (!this._raw) {
  2640. this._binormals[0].normalize();
  2641. }
  2642. this._distances[0] = 0;
  2643. // normals and binormals : next points
  2644. var prev; // previous vector (segment)
  2645. var cur; // current vector (segment)
  2646. var curTang; // current tangent
  2647. // previous normal
  2648. var prevBinor; // previous binormal
  2649. for (var i = 1; i < l; i++) {
  2650. // tangents
  2651. prev = this._getLastNonNullVector(i);
  2652. if (i < l - 1) {
  2653. cur = this._getFirstNonNullVector(i);
  2654. this._tangents[i] = prev.add(cur);
  2655. this._tangents[i].normalize();
  2656. }
  2657. this._distances[i] = this._distances[i - 1] + prev.length();
  2658. // normals and binormals
  2659. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2660. curTang = this._tangents[i];
  2661. prevBinor = this._binormals[i - 1];
  2662. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2663. if (!this._raw) {
  2664. this._normals[i].normalize();
  2665. }
  2666. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2667. if (!this._raw) {
  2668. this._binormals[i].normalize();
  2669. }
  2670. }
  2671. };
  2672. // private function getFirstNonNullVector(index)
  2673. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2674. Path3D.prototype._getFirstNonNullVector = function (index) {
  2675. var i = 1;
  2676. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2677. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2678. i++;
  2679. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2680. }
  2681. return nNVector;
  2682. };
  2683. // private function getLastNonNullVector(index)
  2684. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2685. Path3D.prototype._getLastNonNullVector = function (index) {
  2686. var i = 1;
  2687. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2688. while (nLVector.length() === 0 && index > i + 1) {
  2689. i++;
  2690. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2691. }
  2692. return nLVector;
  2693. };
  2694. // private function normalVector(v0, vt, va) :
  2695. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2696. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2697. Path3D.prototype._normalVector = function (v0, vt, va) {
  2698. var normal0;
  2699. if (va === undefined || va === null) {
  2700. var point;
  2701. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2702. point = new Vector3(0, -1, 0);
  2703. }
  2704. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2705. point = new Vector3(1, 0, 0);
  2706. }
  2707. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2708. point = new Vector3(0, 0, 1);
  2709. }
  2710. normal0 = Vector3.Cross(vt, point);
  2711. }
  2712. else {
  2713. normal0 = Vector3.Cross(vt, va);
  2714. Vector3.CrossToRef(normal0, vt, normal0);
  2715. }
  2716. normal0.normalize();
  2717. return normal0;
  2718. };
  2719. return Path3D;
  2720. })();
  2721. BABYLON.Path3D = Path3D;
  2722. var Curve3 = (function () {
  2723. /**
  2724. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2725. * A Curve3 is designed from a series of successive Vector3.
  2726. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2727. */
  2728. function Curve3(points) {
  2729. this._length = 0;
  2730. this._points = points;
  2731. this._length = this._computeLength(points);
  2732. }
  2733. /**
  2734. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2735. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2736. * @param v1 (Vector3) the control point
  2737. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2738. * @param nbPoints (integer) the wanted number of points in the curve
  2739. */
  2740. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2741. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2742. var bez = new Array();
  2743. var equation = function (t, val0, val1, val2) {
  2744. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2745. return res;
  2746. };
  2747. for (var i = 0; i <= nbPoints; i++) {
  2748. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2749. }
  2750. return new Curve3(bez);
  2751. };
  2752. /**
  2753. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2754. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2755. * @param v1 (Vector3) the first control point
  2756. * @param v2 (Vector3) the second control point
  2757. * @param v3 (Vector3) the end point of the Cubic Bezier
  2758. * @param nbPoints (integer) the wanted number of points in the curve
  2759. */
  2760. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2761. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2762. var bez = new Array();
  2763. var equation = function (t, val0, val1, val2, val3) {
  2764. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2765. return res;
  2766. };
  2767. for (var i = 0; i <= nbPoints; i++) {
  2768. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2769. }
  2770. return new Curve3(bez);
  2771. };
  2772. /**
  2773. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2774. * @param p1 (Vector3) the origin point of the Hermite Spline
  2775. * @param t1 (Vector3) the tangent vector at the origin point
  2776. * @param p2 (Vector3) the end point of the Hermite Spline
  2777. * @param t2 (Vector3) the tangent vector at the end point
  2778. * @param nbPoints (integer) the wanted number of points in the curve
  2779. */
  2780. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2781. var hermite = new Array();
  2782. var step = 1 / nbPoints;
  2783. for (var i = 0; i <= nbPoints; i++) {
  2784. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2785. }
  2786. return new Curve3(hermite);
  2787. };
  2788. /**
  2789. * Returns the Curve3 stored array of successive Vector3
  2790. */
  2791. Curve3.prototype.getPoints = function () {
  2792. return this._points;
  2793. };
  2794. /**
  2795. * Returns the computed length (float) of the curve.
  2796. */
  2797. Curve3.prototype.length = function () {
  2798. return this._length;
  2799. };
  2800. /**
  2801. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2802. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2803. * curveA and curveB keep unchanged.
  2804. */
  2805. Curve3.prototype.continue = function (curve) {
  2806. var lastPoint = this._points[this._points.length - 1];
  2807. var continuedPoints = this._points.slice();
  2808. var curvePoints = curve.getPoints();
  2809. for (var i = 1; i < curvePoints.length; i++) {
  2810. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2811. }
  2812. var continuedCurve = new Curve3(continuedPoints);
  2813. return continuedCurve;
  2814. };
  2815. Curve3.prototype._computeLength = function (path) {
  2816. var l = 0;
  2817. for (var i = 1; i < path.length; i++) {
  2818. l += (path[i].subtract(path[i - 1])).length();
  2819. }
  2820. return l;
  2821. };
  2822. return Curve3;
  2823. })();
  2824. BABYLON.Curve3 = Curve3;
  2825. // SphericalHarmonics
  2826. var SphericalHarmonics = (function () {
  2827. function SphericalHarmonics() {
  2828. this.L00 = Vector3.Zero();
  2829. this.L1_1 = Vector3.Zero();
  2830. this.L10 = Vector3.Zero();
  2831. this.L11 = Vector3.Zero();
  2832. this.L2_2 = Vector3.Zero();
  2833. this.L2_1 = Vector3.Zero();
  2834. this.L20 = Vector3.Zero();
  2835. this.L21 = Vector3.Zero();
  2836. this.L22 = Vector3.Zero();
  2837. }
  2838. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2839. var colorVector = new Vector3(color.r, color.g, color.b);
  2840. var c = colorVector.scale(deltaSolidAngle);
  2841. this.L00 = this.L00.add(c.scale(0.282095));
  2842. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2843. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2844. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2845. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2846. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2847. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2848. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2849. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2850. };
  2851. SphericalHarmonics.prototype.scale = function (scale) {
  2852. this.L00 = this.L00.scale(scale);
  2853. this.L1_1 = this.L1_1.scale(scale);
  2854. this.L10 = this.L10.scale(scale);
  2855. this.L11 = this.L11.scale(scale);
  2856. this.L2_2 = this.L2_2.scale(scale);
  2857. this.L2_1 = this.L2_1.scale(scale);
  2858. this.L20 = this.L20.scale(scale);
  2859. this.L21 = this.L21.scale(scale);
  2860. this.L22 = this.L22.scale(scale);
  2861. };
  2862. return SphericalHarmonics;
  2863. })();
  2864. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2865. // SphericalPolynomial
  2866. var SphericalPolynomial = (function () {
  2867. function SphericalPolynomial() {
  2868. this.x = Vector3.Zero();
  2869. this.y = Vector3.Zero();
  2870. this.z = Vector3.Zero();
  2871. this.xx = Vector3.Zero();
  2872. this.yy = Vector3.Zero();
  2873. this.zz = Vector3.Zero();
  2874. this.xy = Vector3.Zero();
  2875. this.yz = Vector3.Zero();
  2876. this.zx = Vector3.Zero();
  2877. }
  2878. SphericalPolynomial.prototype.addAmbient = function (color) {
  2879. var colorVector = new Vector3(color.r, color.g, color.b);
  2880. this.xx = this.xx.add(colorVector);
  2881. this.yy = this.yy.add(colorVector);
  2882. this.zz = this.zz.add(colorVector);
  2883. };
  2884. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2885. var result = new SphericalPolynomial();
  2886. result.x = harmonics.L11.scale(1.02333);
  2887. result.y = harmonics.L1_1.scale(1.02333);
  2888. result.z = harmonics.L10.scale(1.02333);
  2889. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2890. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2891. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2892. result.yz = harmonics.L2_1.scale(0.858086);
  2893. result.zx = harmonics.L21.scale(0.858086);
  2894. result.xy = harmonics.L2_2.scale(0.858086);
  2895. return result;
  2896. };
  2897. return SphericalPolynomial;
  2898. })();
  2899. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2900. // Vertex formats
  2901. var PositionNormalVertex = (function () {
  2902. function PositionNormalVertex(position, normal) {
  2903. if (position === void 0) { position = Vector3.Zero(); }
  2904. if (normal === void 0) { normal = Vector3.Up(); }
  2905. this.position = position;
  2906. this.normal = normal;
  2907. }
  2908. PositionNormalVertex.prototype.clone = function () {
  2909. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2910. };
  2911. return PositionNormalVertex;
  2912. })();
  2913. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2914. var PositionNormalTextureVertex = (function () {
  2915. function PositionNormalTextureVertex(position, normal, uv) {
  2916. if (position === void 0) { position = Vector3.Zero(); }
  2917. if (normal === void 0) { normal = Vector3.Up(); }
  2918. if (uv === void 0) { uv = Vector2.Zero(); }
  2919. this.position = position;
  2920. this.normal = normal;
  2921. this.uv = uv;
  2922. }
  2923. PositionNormalTextureVertex.prototype.clone = function () {
  2924. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2925. };
  2926. return PositionNormalTextureVertex;
  2927. })();
  2928. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2929. // Temporary pre-allocated objects for engine internal use
  2930. // usage in any internal function :
  2931. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2932. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2933. var Tmp = (function () {
  2934. function Tmp() {
  2935. }
  2936. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2937. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2938. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2939. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2940. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2941. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2942. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2943. Matrix.Zero(), Matrix.Zero(),
  2944. Matrix.Zero(), Matrix.Zero(),
  2945. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2946. return Tmp;
  2947. })();
  2948. BABYLON.Tmp = Tmp;
  2949. })(BABYLON || (BABYLON = {}));
  2950. var BABYLON;
  2951. (function (BABYLON) {
  2952. function generateSerializableMember(type, sourceName) {
  2953. return function (target, propertyKey) {
  2954. if (!target.__serializableMembers) {
  2955. target.__serializableMembers = {};
  2956. }
  2957. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2958. };
  2959. }
  2960. function serialize(sourceName) {
  2961. return generateSerializableMember(0, sourceName); // value member
  2962. }
  2963. BABYLON.serialize = serialize;
  2964. function serializeAsTexture(sourceName) {
  2965. return generateSerializableMember(1, sourceName); // texture member
  2966. }
  2967. BABYLON.serializeAsTexture = serializeAsTexture;
  2968. function serializeAsColor3(sourceName) {
  2969. return generateSerializableMember(2, sourceName); // color3 member
  2970. }
  2971. BABYLON.serializeAsColor3 = serializeAsColor3;
  2972. function serializeAsFresnelParameters(sourceName) {
  2973. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2974. }
  2975. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2976. function serializeAsVector2(sourceName) {
  2977. return generateSerializableMember(4, sourceName); // vector2 member
  2978. }
  2979. BABYLON.serializeAsVector2 = serializeAsVector2;
  2980. function serializeAsVector3(sourceName) {
  2981. return generateSerializableMember(5, sourceName); // vector3 member
  2982. }
  2983. BABYLON.serializeAsVector3 = serializeAsVector3;
  2984. function serializeAsMeshReference(sourceName) {
  2985. return generateSerializableMember(6, sourceName); // mesh reference member
  2986. }
  2987. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2988. var SerializationHelper = (function () {
  2989. function SerializationHelper() {
  2990. }
  2991. SerializationHelper.Serialize = function (entity, serializationObject) {
  2992. if (!serializationObject) {
  2993. serializationObject = {};
  2994. }
  2995. // Tags
  2996. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2997. // Properties
  2998. for (var property in entity.__serializableMembers) {
  2999. var propertyDescriptor = entity.__serializableMembers[property];
  3000. var targetPropertyName = propertyDescriptor.sourceName || property;
  3001. var propertyType = propertyDescriptor.type;
  3002. var sourceProperty = entity[property];
  3003. if (sourceProperty !== undefined && sourceProperty !== null) {
  3004. switch (propertyType) {
  3005. case 0:
  3006. serializationObject[targetPropertyName] = sourceProperty;
  3007. break;
  3008. case 1:
  3009. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3010. break;
  3011. case 2:
  3012. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3013. break;
  3014. case 3:
  3015. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3016. break;
  3017. case 4:
  3018. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3019. break;
  3020. case 5:
  3021. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3022. break;
  3023. case 6:
  3024. serializationObject[targetPropertyName] = sourceProperty.id;
  3025. break;
  3026. }
  3027. }
  3028. }
  3029. return serializationObject;
  3030. };
  3031. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3032. var destination = creationFunction();
  3033. // Tags
  3034. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3035. // Properties
  3036. for (var property in destination.__serializableMembers) {
  3037. var propertyDescriptor = destination.__serializableMembers[property];
  3038. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3039. var propertyType = propertyDescriptor.type;
  3040. if (sourceProperty !== undefined && sourceProperty !== null) {
  3041. switch (propertyType) {
  3042. case 0:
  3043. destination[property] = sourceProperty;
  3044. break;
  3045. case 1:
  3046. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3047. break;
  3048. case 2:
  3049. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3050. break;
  3051. case 3:
  3052. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3053. break;
  3054. case 4:
  3055. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3056. break;
  3057. case 5:
  3058. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3059. break;
  3060. case 6:
  3061. destination[property] = scene.getLastMeshByID(sourceProperty);
  3062. break;
  3063. }
  3064. }
  3065. }
  3066. return destination;
  3067. };
  3068. SerializationHelper.Clone = function (creationFunction, source) {
  3069. var destination = creationFunction();
  3070. // Tags
  3071. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3072. // Properties
  3073. for (var property in destination.__serializableMembers) {
  3074. var propertyDescriptor = destination.__serializableMembers[property];
  3075. var sourceProperty = source[property];
  3076. var propertyType = propertyDescriptor.type;
  3077. if (sourceProperty !== undefined && sourceProperty !== null) {
  3078. switch (propertyType) {
  3079. case 0: // Value
  3080. case 6:
  3081. destination[property] = sourceProperty;
  3082. break;
  3083. case 1: // Texture
  3084. case 2: // Color3
  3085. case 3: // FresnelParameters
  3086. case 4: // Vector2
  3087. case 5:
  3088. destination[property] = sourceProperty.clone();
  3089. break;
  3090. }
  3091. }
  3092. }
  3093. return destination;
  3094. };
  3095. return SerializationHelper;
  3096. })();
  3097. BABYLON.SerializationHelper = SerializationHelper;
  3098. })(BABYLON || (BABYLON = {}));
  3099. var BABYLON;
  3100. (function (BABYLON) {
  3101. /**
  3102. * A class serves as a medium between the observable and its observers
  3103. */
  3104. var EventState = (function () {
  3105. /**
  3106. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3107. */
  3108. function EventState(skipNextObservers) {
  3109. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3110. this.skipNextObservers = skipNextObservers;
  3111. }
  3112. return EventState;
  3113. })();
  3114. BABYLON.EventState = EventState;
  3115. var Observer = (function () {
  3116. function Observer(callback, mask) {
  3117. this.callback = callback;
  3118. this.mask = mask;
  3119. }
  3120. return Observer;
  3121. })();
  3122. BABYLON.Observer = Observer;
  3123. var Observable = (function () {
  3124. function Observable() {
  3125. this._observers = new Array();
  3126. }
  3127. /**
  3128. * Create a new Observer with the specified callback
  3129. * @param callback the callback that will be executed for that Observer
  3130. * @param mash the mask used to filter observers
  3131. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3132. */
  3133. Observable.prototype.add = function (callback, mask, insertFirst) {
  3134. if (mask === void 0) { mask = -1; }
  3135. if (insertFirst === void 0) { insertFirst = false; }
  3136. if (!callback) {
  3137. return null;
  3138. }
  3139. var observer = new Observer(callback, mask);
  3140. if (insertFirst) {
  3141. this._observers.unshift(observer);
  3142. }
  3143. else {
  3144. this._observers.push(observer);
  3145. }
  3146. return observer;
  3147. };
  3148. /**
  3149. * Remove an Observer from the Observable object
  3150. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3151. */
  3152. Observable.prototype.remove = function (observer) {
  3153. var index = this._observers.indexOf(observer);
  3154. if (index !== -1) {
  3155. this._observers.splice(index, 1);
  3156. return true;
  3157. }
  3158. return false;
  3159. };
  3160. /**
  3161. * Remove a callback from the Observable object
  3162. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3163. */
  3164. Observable.prototype.removeCallback = function (callback) {
  3165. for (var index = 0; index < this._observers.length; index++) {
  3166. if (this._observers[index].callback === callback) {
  3167. this._observers.splice(index, 1);
  3168. return true;
  3169. }
  3170. }
  3171. return false;
  3172. };
  3173. /**
  3174. * Notify all Observers by calling their respective callback with the given data
  3175. * @param eventData
  3176. * @param mask
  3177. */
  3178. Observable.prototype.notifyObservers = function (eventData, mask) {
  3179. if (mask === void 0) { mask = -1; }
  3180. var state = new EventState();
  3181. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3182. var obs = _a[_i];
  3183. if (obs.mask & mask) {
  3184. obs.callback(eventData, state);
  3185. }
  3186. if (state.skipNextObservers) {
  3187. break;
  3188. }
  3189. }
  3190. };
  3191. /**
  3192. * return true is the Observable has at least one Observer registered
  3193. */
  3194. Observable.prototype.hasObservers = function () {
  3195. return this._observers.length > 0;
  3196. };
  3197. /**
  3198. * Clear the list of observers
  3199. */
  3200. Observable.prototype.clear = function () {
  3201. this._observers = new Array();
  3202. };
  3203. /**
  3204. * Clone the current observable
  3205. */
  3206. Observable.prototype.clone = function () {
  3207. var result = new Observable();
  3208. result._observers = this._observers.slice(0);
  3209. return result;
  3210. };
  3211. return Observable;
  3212. })();
  3213. BABYLON.Observable = Observable;
  3214. })(BABYLON || (BABYLON = {}));
  3215. var BABYLON;
  3216. (function (BABYLON) {
  3217. var Database = (function () {
  3218. function Database(urlToScene, callbackManifestChecked) {
  3219. // Handling various flavors of prefixed version of IndexedDB
  3220. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3221. this.callbackManifestChecked = callbackManifestChecked;
  3222. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3223. this.db = null;
  3224. this.enableSceneOffline = false;
  3225. this.enableTexturesOffline = false;
  3226. this.manifestVersionFound = 0;
  3227. this.mustUpdateRessources = false;
  3228. this.hasReachedQuota = false;
  3229. if (!Database.IDBStorageEnabled) {
  3230. this.callbackManifestChecked(true);
  3231. }
  3232. else {
  3233. this.checkManifestFile();
  3234. }
  3235. }
  3236. Database.prototype.checkManifestFile = function () {
  3237. var _this = this;
  3238. function noManifestFile() {
  3239. that.enableSceneOffline = false;
  3240. that.enableTexturesOffline = false;
  3241. that.callbackManifestChecked(false);
  3242. }
  3243. var that = this;
  3244. var timeStampUsed = false;
  3245. var manifestURL = this.currentSceneUrl + ".manifest";
  3246. var xhr = new XMLHttpRequest();
  3247. if (navigator.onLine) {
  3248. // Adding a timestamp to by-pass browsers' cache
  3249. timeStampUsed = true;
  3250. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3251. }
  3252. xhr.open("GET", manifestURL, true);
  3253. xhr.addEventListener("load", function () {
  3254. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3255. try {
  3256. var manifestFile = JSON.parse(xhr.response);
  3257. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3258. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3259. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3260. _this.manifestVersionFound = manifestFile.version;
  3261. }
  3262. if (_this.callbackManifestChecked) {
  3263. _this.callbackManifestChecked(true);
  3264. }
  3265. }
  3266. catch (ex) {
  3267. noManifestFile();
  3268. }
  3269. }
  3270. else {
  3271. noManifestFile();
  3272. }
  3273. }, false);
  3274. xhr.addEventListener("error", function (event) {
  3275. if (timeStampUsed) {
  3276. timeStampUsed = false;
  3277. // Let's retry without the timeStamp
  3278. // It could fail when coupled with HTML5 Offline API
  3279. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3280. xhr.open("GET", retryManifestURL, true);
  3281. xhr.send();
  3282. }
  3283. else {
  3284. noManifestFile();
  3285. }
  3286. }, false);
  3287. try {
  3288. xhr.send();
  3289. }
  3290. catch (ex) {
  3291. BABYLON.Tools.Error("Error on XHR send request.");
  3292. that.callbackManifestChecked(false);
  3293. }
  3294. };
  3295. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3296. var _this = this;
  3297. function handleError() {
  3298. that.isSupported = false;
  3299. if (errorCallback)
  3300. errorCallback();
  3301. }
  3302. var that = this;
  3303. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3304. // Your browser doesn't support IndexedDB
  3305. this.isSupported = false;
  3306. if (errorCallback)
  3307. errorCallback();
  3308. }
  3309. else {
  3310. // If the DB hasn't been opened or created yet
  3311. if (!this.db) {
  3312. this.hasReachedQuota = false;
  3313. this.isSupported = true;
  3314. var request = this.idbFactory.open("babylonjs", 1);
  3315. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3316. request.onerror = function (event) {
  3317. handleError();
  3318. };
  3319. // executes when a version change transaction cannot complete due to other active transactions
  3320. request.onblocked = function (event) {
  3321. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3322. handleError();
  3323. };
  3324. // DB has been opened successfully
  3325. request.onsuccess = function (event) {
  3326. _this.db = request.result;
  3327. successCallback();
  3328. };
  3329. // Initialization of the DB. Creating Scenes & Textures stores
  3330. request.onupgradeneeded = function (event) {
  3331. _this.db = (event.target).result;
  3332. try {
  3333. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3334. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3335. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3336. }
  3337. catch (ex) {
  3338. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3339. handleError();
  3340. }
  3341. };
  3342. }
  3343. else {
  3344. if (successCallback)
  3345. successCallback();
  3346. }
  3347. }
  3348. };
  3349. Database.prototype.loadImageFromDB = function (url, image) {
  3350. var _this = this;
  3351. var completeURL = Database.ReturnFullUrlLocation(url);
  3352. var saveAndLoadImage = function () {
  3353. if (!_this.hasReachedQuota && _this.db !== null) {
  3354. // the texture is not yet in the DB, let's try to save it
  3355. _this._saveImageIntoDBAsync(completeURL, image);
  3356. }
  3357. else {
  3358. image.src = url;
  3359. }
  3360. };
  3361. if (!this.mustUpdateRessources) {
  3362. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3363. }
  3364. else {
  3365. saveAndLoadImage();
  3366. }
  3367. };
  3368. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3369. if (this.isSupported && this.db !== null) {
  3370. var texture;
  3371. var transaction = this.db.transaction(["textures"]);
  3372. transaction.onabort = function (event) {
  3373. image.src = url;
  3374. };
  3375. transaction.oncomplete = function (event) {
  3376. var blobTextureURL;
  3377. if (texture) {
  3378. var URL = window.URL || window.webkitURL;
  3379. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3380. image.onerror = function () {
  3381. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3382. image.src = url;
  3383. };
  3384. image.src = blobTextureURL;
  3385. }
  3386. else {
  3387. notInDBCallback();
  3388. }
  3389. };
  3390. var getRequest = transaction.objectStore("textures").get(url);
  3391. getRequest.onsuccess = function (event) {
  3392. texture = (event.target).result;
  3393. };
  3394. getRequest.onerror = function (event) {
  3395. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3396. image.src = url;
  3397. };
  3398. }
  3399. else {
  3400. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3401. image.src = url;
  3402. }
  3403. };
  3404. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3405. var _this = this;
  3406. if (this.isSupported) {
  3407. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3408. var generateBlobUrl = function () {
  3409. var blobTextureURL;
  3410. if (blob) {
  3411. var URL = window.URL || window.webkitURL;
  3412. try {
  3413. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3414. }
  3415. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3416. catch (ex) {
  3417. blobTextureURL = URL.createObjectURL(blob);
  3418. }
  3419. }
  3420. image.src = blobTextureURL;
  3421. };
  3422. if (Database.IsUASupportingBlobStorage) {
  3423. var xhr = new XMLHttpRequest(), blob;
  3424. xhr.open("GET", url, true);
  3425. xhr.responseType = "blob";
  3426. xhr.addEventListener("load", function () {
  3427. if (xhr.status === 200) {
  3428. // Blob as response (XHR2)
  3429. blob = xhr.response;
  3430. var transaction = _this.db.transaction(["textures"], "readwrite");
  3431. // the transaction could abort because of a QuotaExceededError error
  3432. transaction.onabort = function (event) {
  3433. try {
  3434. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3435. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3436. this.hasReachedQuota = true;
  3437. }
  3438. }
  3439. catch (ex) { }
  3440. generateBlobUrl();
  3441. };
  3442. transaction.oncomplete = function (event) {
  3443. generateBlobUrl();
  3444. };
  3445. var newTexture = { textureUrl: url, data: blob };
  3446. try {
  3447. // Put the blob into the dabase
  3448. var addRequest = transaction.objectStore("textures").put(newTexture);
  3449. addRequest.onsuccess = function (event) {
  3450. };
  3451. addRequest.onerror = function (event) {
  3452. generateBlobUrl();
  3453. };
  3454. }
  3455. catch (ex) {
  3456. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3457. if (ex.code === 25) {
  3458. Database.IsUASupportingBlobStorage = false;
  3459. }
  3460. image.src = url;
  3461. }
  3462. }
  3463. else {
  3464. image.src = url;
  3465. }
  3466. }, false);
  3467. xhr.addEventListener("error", function (event) {
  3468. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3469. image.src = url;
  3470. }, false);
  3471. xhr.send();
  3472. }
  3473. else {
  3474. image.src = url;
  3475. }
  3476. }
  3477. else {
  3478. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3479. image.src = url;
  3480. }
  3481. };
  3482. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3483. var _this = this;
  3484. var updateVersion = function (event) {
  3485. // the version is not yet in the DB or we need to update it
  3486. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3487. };
  3488. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3489. };
  3490. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3491. var _this = this;
  3492. if (this.isSupported) {
  3493. var version;
  3494. try {
  3495. var transaction = this.db.transaction(["versions"]);
  3496. transaction.oncomplete = function (event) {
  3497. if (version) {
  3498. // If the version in the JSON file is > than the version in DB
  3499. if (_this.manifestVersionFound > version.data) {
  3500. _this.mustUpdateRessources = true;
  3501. updateInDBCallback();
  3502. }
  3503. else {
  3504. callback(version.data);
  3505. }
  3506. }
  3507. else {
  3508. _this.mustUpdateRessources = true;
  3509. updateInDBCallback();
  3510. }
  3511. };
  3512. transaction.onabort = function (event) {
  3513. callback(-1);
  3514. };
  3515. var getRequest = transaction.objectStore("versions").get(url);
  3516. getRequest.onsuccess = function (event) {
  3517. version = (event.target).result;
  3518. };
  3519. getRequest.onerror = function (event) {
  3520. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3521. callback(-1);
  3522. };
  3523. }
  3524. catch (ex) {
  3525. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3526. callback(-1);
  3527. }
  3528. }
  3529. else {
  3530. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3531. callback(-1);
  3532. }
  3533. };
  3534. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3535. var _this = this;
  3536. if (this.isSupported && !this.hasReachedQuota) {
  3537. try {
  3538. // Open a transaction to the database
  3539. var transaction = this.db.transaction(["versions"], "readwrite");
  3540. // the transaction could abort because of a QuotaExceededError error
  3541. transaction.onabort = function (event) {
  3542. try {
  3543. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3544. _this.hasReachedQuota = true;
  3545. }
  3546. }
  3547. catch (ex) { }
  3548. callback(-1);
  3549. };
  3550. transaction.oncomplete = function (event) {
  3551. callback(_this.manifestVersionFound);
  3552. };
  3553. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3554. // Put the scene into the database
  3555. var addRequest = transaction.objectStore("versions").put(newVersion);
  3556. addRequest.onsuccess = function (event) {
  3557. };
  3558. addRequest.onerror = function (event) {
  3559. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3560. };
  3561. }
  3562. catch (ex) {
  3563. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3564. callback(-1);
  3565. }
  3566. }
  3567. else {
  3568. callback(-1);
  3569. }
  3570. };
  3571. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3572. var _this = this;
  3573. var completeUrl = Database.ReturnFullUrlLocation(url);
  3574. var saveAndLoadFile = function (event) {
  3575. // the scene is not yet in the DB, let's try to save it
  3576. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3577. };
  3578. this._checkVersionFromDB(completeUrl, function (version) {
  3579. if (version !== -1) {
  3580. if (!_this.mustUpdateRessources) {
  3581. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3582. }
  3583. else {
  3584. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3585. }
  3586. }
  3587. else {
  3588. errorCallback();
  3589. }
  3590. });
  3591. };
  3592. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3593. if (this.isSupported) {
  3594. var targetStore;
  3595. if (url.indexOf(".babylon") !== -1) {
  3596. targetStore = "scenes";
  3597. }
  3598. else {
  3599. targetStore = "textures";
  3600. }
  3601. var file;
  3602. var transaction = this.db.transaction([targetStore]);
  3603. transaction.oncomplete = function (event) {
  3604. if (file) {
  3605. callback(file.data);
  3606. }
  3607. else {
  3608. notInDBCallback();
  3609. }
  3610. };
  3611. transaction.onabort = function (event) {
  3612. notInDBCallback();
  3613. };
  3614. var getRequest = transaction.objectStore(targetStore).get(url);
  3615. getRequest.onsuccess = function (event) {
  3616. file = (event.target).result;
  3617. };
  3618. getRequest.onerror = function (event) {
  3619. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3620. notInDBCallback();
  3621. };
  3622. }
  3623. else {
  3624. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3625. callback();
  3626. }
  3627. };
  3628. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3629. var _this = this;
  3630. if (this.isSupported) {
  3631. var targetStore;
  3632. if (url.indexOf(".babylon") !== -1) {
  3633. targetStore = "scenes";
  3634. }
  3635. else {
  3636. targetStore = "textures";
  3637. }
  3638. // Create XHR
  3639. var xhr = new XMLHttpRequest(), fileData;
  3640. xhr.open("GET", url, true);
  3641. if (useArrayBuffer) {
  3642. xhr.responseType = "arraybuffer";
  3643. }
  3644. xhr.onprogress = progressCallback;
  3645. xhr.addEventListener("load", function () {
  3646. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3647. // Blob as response (XHR2)
  3648. //fileData = xhr.responseText;
  3649. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3650. if (!_this.hasReachedQuota) {
  3651. // Open a transaction to the database
  3652. var transaction = _this.db.transaction([targetStore], "readwrite");
  3653. // the transaction could abort because of a QuotaExceededError error
  3654. transaction.onabort = function (event) {
  3655. try {
  3656. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3657. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3658. this.hasReachedQuota = true;
  3659. }
  3660. }
  3661. catch (ex) { }
  3662. callback(fileData);
  3663. };
  3664. transaction.oncomplete = function (event) {
  3665. callback(fileData);
  3666. };
  3667. var newFile;
  3668. if (targetStore === "scenes") {
  3669. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3670. }
  3671. else {
  3672. newFile = { textureUrl: url, data: fileData };
  3673. }
  3674. try {
  3675. // Put the scene into the database
  3676. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3677. addRequest.onsuccess = function (event) {
  3678. };
  3679. addRequest.onerror = function (event) {
  3680. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3681. };
  3682. }
  3683. catch (ex) {
  3684. callback(fileData);
  3685. }
  3686. }
  3687. else {
  3688. callback(fileData);
  3689. }
  3690. }
  3691. else {
  3692. callback();
  3693. }
  3694. }, false);
  3695. xhr.addEventListener("error", function (event) {
  3696. BABYLON.Tools.Error("error on XHR request.");
  3697. callback();
  3698. }, false);
  3699. xhr.send();
  3700. }
  3701. else {
  3702. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3703. callback();
  3704. }
  3705. };
  3706. Database.IsUASupportingBlobStorage = true;
  3707. Database.IDBStorageEnabled = true;
  3708. Database.parseURL = function (url) {
  3709. var a = document.createElement('a');
  3710. a.href = url;
  3711. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3712. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3713. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3714. return absLocation;
  3715. };
  3716. Database.ReturnFullUrlLocation = function (url) {
  3717. if (url.indexOf("http:/") === -1) {
  3718. return (Database.parseURL(window.location.href) + url);
  3719. }
  3720. else {
  3721. return url;
  3722. }
  3723. };
  3724. return Database;
  3725. })();
  3726. BABYLON.Database = Database;
  3727. })(BABYLON || (BABYLON = {}));
  3728. var BABYLON;
  3729. (function (BABYLON) {
  3730. var Internals;
  3731. (function (Internals) {
  3732. /*
  3733. * Based on jsTGALoader - Javascript loader for TGA file
  3734. * By Vincent Thibault
  3735. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3736. */
  3737. var TGATools = (function () {
  3738. function TGATools() {
  3739. }
  3740. TGATools.GetTGAHeader = function (data) {
  3741. var offset = 0;
  3742. var header = {
  3743. id_length: data[offset++],
  3744. colormap_type: data[offset++],
  3745. image_type: data[offset++],
  3746. colormap_index: data[offset++] | data[offset++] << 8,
  3747. colormap_length: data[offset++] | data[offset++] << 8,
  3748. colormap_size: data[offset++],
  3749. origin: [
  3750. data[offset++] | data[offset++] << 8,
  3751. data[offset++] | data[offset++] << 8
  3752. ],
  3753. width: data[offset++] | data[offset++] << 8,
  3754. height: data[offset++] | data[offset++] << 8,
  3755. pixel_size: data[offset++],
  3756. flags: data[offset++]
  3757. };
  3758. return header;
  3759. };
  3760. TGATools.UploadContent = function (gl, data) {
  3761. // Not enough data to contain header ?
  3762. if (data.length < 19) {
  3763. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3764. return;
  3765. }
  3766. // Read Header
  3767. var offset = 18;
  3768. var header = TGATools.GetTGAHeader(data);
  3769. // Assume it's a valid Targa file.
  3770. if (header.id_length + offset > data.length) {
  3771. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3772. return;
  3773. }
  3774. // Skip not needed data
  3775. offset += header.id_length;
  3776. var use_rle = false;
  3777. var use_pal = false;
  3778. var use_rgb = false;
  3779. var use_grey = false;
  3780. // Get some informations.
  3781. switch (header.image_type) {
  3782. case TGATools._TYPE_RLE_INDEXED:
  3783. use_rle = true;
  3784. case TGATools._TYPE_INDEXED:
  3785. use_pal = true;
  3786. break;
  3787. case TGATools._TYPE_RLE_RGB:
  3788. use_rle = true;
  3789. case TGATools._TYPE_RGB:
  3790. use_rgb = true;
  3791. break;
  3792. case TGATools._TYPE_RLE_GREY:
  3793. use_rle = true;
  3794. case TGATools._TYPE_GREY:
  3795. use_grey = true;
  3796. break;
  3797. }
  3798. var pixel_data;
  3799. var numAlphaBits = header.flags & 0xf;
  3800. var pixel_size = header.pixel_size >> 3;
  3801. var pixel_total = header.width * header.height * pixel_size;
  3802. // Read palettes
  3803. var palettes;
  3804. if (use_pal) {
  3805. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3806. }
  3807. // Read LRE
  3808. if (use_rle) {
  3809. pixel_data = new Uint8Array(pixel_total);
  3810. var c, count, i;
  3811. var localOffset = 0;
  3812. var pixels = new Uint8Array(pixel_size);
  3813. while (offset < pixel_total && localOffset < pixel_total) {
  3814. c = data[offset++];
  3815. count = (c & 0x7f) + 1;
  3816. // RLE pixels
  3817. if (c & 0x80) {
  3818. // Bind pixel tmp array
  3819. for (i = 0; i < pixel_size; ++i) {
  3820. pixels[i] = data[offset++];
  3821. }
  3822. // Copy pixel array
  3823. for (i = 0; i < count; ++i) {
  3824. pixel_data.set(pixels, localOffset + i * pixel_size);
  3825. }
  3826. localOffset += pixel_size * count;
  3827. }
  3828. else {
  3829. count *= pixel_size;
  3830. for (i = 0; i < count; ++i) {
  3831. pixel_data[localOffset + i] = data[offset++];
  3832. }
  3833. localOffset += count;
  3834. }
  3835. }
  3836. }
  3837. else {
  3838. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3839. }
  3840. // Load to texture
  3841. var x_start, y_start, x_step, y_step, y_end, x_end;
  3842. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3843. default:
  3844. case TGATools._ORIGIN_UL:
  3845. x_start = 0;
  3846. x_step = 1;
  3847. x_end = header.width;
  3848. y_start = 0;
  3849. y_step = 1;
  3850. y_end = header.height;
  3851. break;
  3852. case TGATools._ORIGIN_BL:
  3853. x_start = 0;
  3854. x_step = 1;
  3855. x_end = header.width;
  3856. y_start = header.height - 1;
  3857. y_step = -1;
  3858. y_end = -1;
  3859. break;
  3860. case TGATools._ORIGIN_UR:
  3861. x_start = header.width - 1;
  3862. x_step = -1;
  3863. x_end = -1;
  3864. y_start = 0;
  3865. y_step = 1;
  3866. y_end = header.height;
  3867. break;
  3868. case TGATools._ORIGIN_BR:
  3869. x_start = header.width - 1;
  3870. x_step = -1;
  3871. x_end = -1;
  3872. y_start = header.height - 1;
  3873. y_step = -1;
  3874. y_end = -1;
  3875. break;
  3876. }
  3877. // Load the specify method
  3878. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3879. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3880. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3881. };
  3882. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3883. var image = pixel_data, colormap = palettes;
  3884. var width = header.width, height = header.height;
  3885. var color, i = 0, x, y;
  3886. var imageData = new Uint8Array(width * height * 4);
  3887. for (y = y_start; y !== y_end; y += y_step) {
  3888. for (x = x_start; x !== x_end; x += x_step, i++) {
  3889. color = image[i];
  3890. imageData[(x + width * y) * 4 + 3] = 255;
  3891. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3892. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3893. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3894. }
  3895. }
  3896. return imageData;
  3897. };
  3898. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3899. var image = pixel_data;
  3900. var width = header.width, height = header.height;
  3901. var color, i = 0, x, y;
  3902. var imageData = new Uint8Array(width * height * 4);
  3903. for (y = y_start; y !== y_end; y += y_step) {
  3904. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3905. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3906. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3907. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3908. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3909. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3910. }
  3911. }
  3912. return imageData;
  3913. };
  3914. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3915. var image = pixel_data;
  3916. var width = header.width, height = header.height;
  3917. var i = 0, x, y;
  3918. var imageData = new Uint8Array(width * height * 4);
  3919. for (y = y_start; y !== y_end; y += y_step) {
  3920. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3921. imageData[(x + width * y) * 4 + 3] = 255;
  3922. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3923. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3924. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3925. }
  3926. }
  3927. return imageData;
  3928. };
  3929. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3930. var image = pixel_data;
  3931. var width = header.width, height = header.height;
  3932. var i = 0, x, y;
  3933. var imageData = new Uint8Array(width * height * 4);
  3934. for (y = y_start; y !== y_end; y += y_step) {
  3935. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3936. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3937. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3938. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3939. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3940. }
  3941. }
  3942. return imageData;
  3943. };
  3944. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3945. var image = pixel_data;
  3946. var width = header.width, height = header.height;
  3947. var color, i = 0, x, y;
  3948. var imageData = new Uint8Array(width * height * 4);
  3949. for (y = y_start; y !== y_end; y += y_step) {
  3950. for (x = x_start; x !== x_end; x += x_step, i++) {
  3951. color = image[i];
  3952. imageData[(x + width * y) * 4 + 0] = color;
  3953. imageData[(x + width * y) * 4 + 1] = color;
  3954. imageData[(x + width * y) * 4 + 2] = color;
  3955. imageData[(x + width * y) * 4 + 3] = 255;
  3956. }
  3957. }
  3958. return imageData;
  3959. };
  3960. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3961. var image = pixel_data;
  3962. var width = header.width, height = header.height;
  3963. var i = 0, x, y;
  3964. var imageData = new Uint8Array(width * height * 4);
  3965. for (y = y_start; y !== y_end; y += y_step) {
  3966. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3967. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3968. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3969. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3970. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3971. }
  3972. }
  3973. return imageData;
  3974. };
  3975. TGATools._TYPE_NO_DATA = 0;
  3976. TGATools._TYPE_INDEXED = 1;
  3977. TGATools._TYPE_RGB = 2;
  3978. TGATools._TYPE_GREY = 3;
  3979. TGATools._TYPE_RLE_INDEXED = 9;
  3980. TGATools._TYPE_RLE_RGB = 10;
  3981. TGATools._TYPE_RLE_GREY = 11;
  3982. TGATools._ORIGIN_MASK = 0x30;
  3983. TGATools._ORIGIN_SHIFT = 0x04;
  3984. TGATools._ORIGIN_BL = 0x00;
  3985. TGATools._ORIGIN_BR = 0x01;
  3986. TGATools._ORIGIN_UL = 0x02;
  3987. TGATools._ORIGIN_UR = 0x03;
  3988. return TGATools;
  3989. })();
  3990. Internals.TGATools = TGATools;
  3991. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3992. })(BABYLON || (BABYLON = {}));
  3993. var BABYLON;
  3994. (function (BABYLON) {
  3995. var SmartArray = (function () {
  3996. function SmartArray(capacity) {
  3997. this.length = 0;
  3998. this._duplicateId = 0;
  3999. this.data = new Array(capacity);
  4000. this._id = SmartArray._GlobalId++;
  4001. }
  4002. SmartArray.prototype.push = function (value) {
  4003. this.data[this.length++] = value;
  4004. if (this.length > this.data.length) {
  4005. this.data.length *= 2;
  4006. }
  4007. if (!value.__smartArrayFlags) {
  4008. value.__smartArrayFlags = {};
  4009. }
  4010. value.__smartArrayFlags[this._id] = this._duplicateId;
  4011. };
  4012. SmartArray.prototype.pushNoDuplicate = function (value) {
  4013. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4014. return;
  4015. }
  4016. this.push(value);
  4017. };
  4018. SmartArray.prototype.sort = function (compareFn) {
  4019. this.data.sort(compareFn);
  4020. };
  4021. SmartArray.prototype.reset = function () {
  4022. this.length = 0;
  4023. this._duplicateId++;
  4024. };
  4025. SmartArray.prototype.concat = function (array) {
  4026. if (array.length === 0) {
  4027. return;
  4028. }
  4029. if (this.length + array.length > this.data.length) {
  4030. this.data.length = (this.length + array.length) * 2;
  4031. }
  4032. for (var index = 0; index < array.length; index++) {
  4033. this.data[this.length++] = (array.data || array)[index];
  4034. }
  4035. };
  4036. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4037. if (array.length === 0) {
  4038. return;
  4039. }
  4040. if (this.length + array.length > this.data.length) {
  4041. this.data.length = (this.length + array.length) * 2;
  4042. }
  4043. for (var index = 0; index < array.length; index++) {
  4044. var item = (array.data || array)[index];
  4045. this.pushNoDuplicate(item);
  4046. }
  4047. };
  4048. SmartArray.prototype.indexOf = function (value) {
  4049. var position = this.data.indexOf(value);
  4050. if (position >= this.length) {
  4051. return -1;
  4052. }
  4053. return position;
  4054. };
  4055. // Statics
  4056. SmartArray._GlobalId = 0;
  4057. return SmartArray;
  4058. })();
  4059. BABYLON.SmartArray = SmartArray;
  4060. })(BABYLON || (BABYLON = {}));
  4061. var BABYLON;
  4062. (function (BABYLON) {
  4063. /**
  4064. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4065. * The underlying implemetation relies on an associative array to ensure the best performances.
  4066. * The value can be anything including 'null' but except 'undefined'
  4067. */
  4068. var StringDictionary = (function () {
  4069. function StringDictionary() {
  4070. this._count = 0;
  4071. this._data = {};
  4072. }
  4073. /**
  4074. * Get a value based from its key
  4075. * @param key the given key to get the matching value from
  4076. * @return the value if found, otherwise undefined is returned
  4077. */
  4078. StringDictionary.prototype.get = function (key) {
  4079. var val = this._data[key];
  4080. if (val !== undefined) {
  4081. return val;
  4082. }
  4083. return undefined;
  4084. };
  4085. /**
  4086. * Get a value from its key or add it if it doesn't exist.
  4087. * This method will ensure you that a given key/data will be present in the dictionary.
  4088. * @param key the given key to get the matchin value from
  4089. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4090. * The factory will only be invoked if there's no data for the given key.
  4091. * @return the value corresponding to the key.
  4092. */
  4093. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4094. var val = this.get(key);
  4095. if (val !== undefined) {
  4096. return val;
  4097. }
  4098. val = factory(key);
  4099. if (val) {
  4100. this.add(key, val);
  4101. }
  4102. return val;
  4103. };
  4104. /**
  4105. * Get a value from its key if present in the dictionary otherwise add it
  4106. * @param key the key to get the value from
  4107. * @param val if there's no such key/value pair in the dictionary add it with this value
  4108. * @return the value corresponding to the key
  4109. */
  4110. StringDictionary.prototype.getOrAdd = function (key, val) {
  4111. var val = this.get(key);
  4112. if (val !== undefined) {
  4113. return val;
  4114. }
  4115. this.add(key, val);
  4116. return val;
  4117. };
  4118. /**
  4119. * Check if there's a given key in the dictionary
  4120. * @param key the key to check for
  4121. * @return true if the key is present, false otherwise
  4122. */
  4123. StringDictionary.prototype.contains = function (key) {
  4124. return this._data[key] !== undefined;
  4125. };
  4126. /**
  4127. * Add a new key and its corresponding value
  4128. * @param key the key to add
  4129. * @param value the value corresponding to the key
  4130. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4131. */
  4132. StringDictionary.prototype.add = function (key, value) {
  4133. if (this._data[key] !== undefined) {
  4134. return false;
  4135. }
  4136. this._data[key] = value;
  4137. ++this._count;
  4138. return true;
  4139. };
  4140. /**
  4141. * Remove a key/value from the dictionary.
  4142. * @param key the key to remove
  4143. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4144. */
  4145. StringDictionary.prototype.remove = function (key) {
  4146. if (this.contains(key)) {
  4147. delete this._data[key];
  4148. --this._count;
  4149. return true;
  4150. }
  4151. return false;
  4152. };
  4153. /**
  4154. * Clear the whole content of the dictionary
  4155. */
  4156. StringDictionary.prototype.clear = function () {
  4157. this._data = {};
  4158. this._count = 0;
  4159. };
  4160. Object.defineProperty(StringDictionary.prototype, "count", {
  4161. get: function () {
  4162. return this._count;
  4163. },
  4164. enumerable: true,
  4165. configurable: true
  4166. });
  4167. /**
  4168. * Execute a callback on each key/val of the dictionary.
  4169. * Note that you can remove any element in this dictionary in the callback implementation
  4170. * @param callback the callback to execute on a given key/value pair
  4171. */
  4172. StringDictionary.prototype.forEach = function (callback) {
  4173. for (var cur in this._data) {
  4174. var val = this._data[cur];
  4175. callback(cur, val);
  4176. }
  4177. };
  4178. /**
  4179. * Execute a callback on every occurence of the dictionary until it returns a valid TRes object.
  4180. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4181. * Note that you can remove any element in this dictionary in the callback implementation
  4182. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4183. */
  4184. StringDictionary.prototype.first = function (callback) {
  4185. for (var cur in this._data) {
  4186. var val = this._data[cur];
  4187. var res = callback(cur, val);
  4188. if (res) {
  4189. return res;
  4190. }
  4191. }
  4192. return null;
  4193. };
  4194. return StringDictionary;
  4195. })();
  4196. BABYLON.StringDictionary = StringDictionary;
  4197. })(BABYLON || (BABYLON = {}));
  4198. var BABYLON;
  4199. (function (BABYLON) {
  4200. // Screenshots
  4201. var screenshotCanvas;
  4202. var cloneValue = function (source, destinationObject) {
  4203. if (!source)
  4204. return null;
  4205. if (source instanceof BABYLON.Mesh) {
  4206. return null;
  4207. }
  4208. if (source instanceof BABYLON.SubMesh) {
  4209. return source.clone(destinationObject);
  4210. }
  4211. else if (source.clone) {
  4212. return source.clone();
  4213. }
  4214. return null;
  4215. };
  4216. var Tools = (function () {
  4217. function Tools() {
  4218. }
  4219. Tools.Instantiate = function (className) {
  4220. var arr = className.split(".");
  4221. var fn = (window || this);
  4222. for (var i = 0, len = arr.length; i < len; i++) {
  4223. fn = fn[arr[i]];
  4224. }
  4225. if (typeof fn !== "function") {
  4226. return null;
  4227. }
  4228. return fn;
  4229. };
  4230. Tools.SetImmediate = function (action) {
  4231. if (window.setImmediate) {
  4232. window.setImmediate(action);
  4233. }
  4234. else {
  4235. setTimeout(action, 1);
  4236. }
  4237. };
  4238. Tools.IsExponentOfTwo = function (value) {
  4239. var count = 1;
  4240. do {
  4241. count *= 2;
  4242. } while (count < value);
  4243. return count === value;
  4244. };
  4245. Tools.GetExponentOfTwo = function (value, max) {
  4246. var count = 1;
  4247. do {
  4248. count *= 2;
  4249. } while (count < value);
  4250. if (count > max)
  4251. count = max;
  4252. return count;
  4253. };
  4254. Tools.GetFilename = function (path) {
  4255. var index = path.lastIndexOf("/");
  4256. if (index < 0)
  4257. return path;
  4258. return path.substring(index + 1);
  4259. };
  4260. Tools.GetDOMTextContent = function (element) {
  4261. var result = "";
  4262. var child = element.firstChild;
  4263. while (child) {
  4264. if (child.nodeType === 3) {
  4265. result += child.textContent;
  4266. }
  4267. child = child.nextSibling;
  4268. }
  4269. return result;
  4270. };
  4271. Tools.ToDegrees = function (angle) {
  4272. return angle * 180 / Math.PI;
  4273. };
  4274. Tools.ToRadians = function (angle) {
  4275. return angle * Math.PI / 180;
  4276. };
  4277. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4278. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4279. var output = "";
  4280. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4281. var i = 0;
  4282. var bytes = new Uint8Array(buffer);
  4283. while (i < bytes.length) {
  4284. chr1 = bytes[i++];
  4285. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4286. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4287. enc1 = chr1 >> 2;
  4288. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4289. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4290. enc4 = chr3 & 63;
  4291. if (isNaN(chr2)) {
  4292. enc3 = enc4 = 64;
  4293. }
  4294. else if (isNaN(chr3)) {
  4295. enc4 = 64;
  4296. }
  4297. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4298. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4299. }
  4300. return "data:image/png;base64," + output;
  4301. };
  4302. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4303. if (bias === void 0) { bias = null; }
  4304. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4305. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4306. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4307. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4308. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4309. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4310. }
  4311. if (bias) {
  4312. minimum.x -= minimum.x * bias.x + bias.y;
  4313. minimum.y -= minimum.y * bias.x + bias.y;
  4314. minimum.z -= minimum.z * bias.x + bias.y;
  4315. maximum.x += maximum.x * bias.x + bias.y;
  4316. maximum.y += maximum.y * bias.x + bias.y;
  4317. maximum.z += maximum.z * bias.x + bias.y;
  4318. }
  4319. return {
  4320. minimum: minimum,
  4321. maximum: maximum
  4322. };
  4323. };
  4324. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4325. if (bias === void 0) { bias = null; }
  4326. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4327. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4328. for (var index = start; index < start + count; index++) {
  4329. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4330. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4331. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4332. }
  4333. if (bias) {
  4334. minimum.x -= minimum.x * bias.x + bias.y;
  4335. minimum.y -= minimum.y * bias.x + bias.y;
  4336. minimum.z -= minimum.z * bias.x + bias.y;
  4337. maximum.x += maximum.x * bias.x + bias.y;
  4338. maximum.y += maximum.y * bias.x + bias.y;
  4339. maximum.z += maximum.z * bias.x + bias.y;
  4340. }
  4341. return {
  4342. minimum: minimum,
  4343. maximum: maximum
  4344. };
  4345. };
  4346. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4347. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4348. return undefined;
  4349. return Array.isArray(obj) ? obj : [obj];
  4350. };
  4351. // Misc.
  4352. Tools.GetPointerPrefix = function () {
  4353. var eventPrefix = "pointer";
  4354. // Check if pointer events are supported
  4355. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4356. eventPrefix = "mouse";
  4357. }
  4358. return eventPrefix;
  4359. };
  4360. Tools.QueueNewFrame = function (func) {
  4361. if (window.requestAnimationFrame)
  4362. window.requestAnimationFrame(func);
  4363. else if (window.msRequestAnimationFrame)
  4364. window.msRequestAnimationFrame(func);
  4365. else if (window.webkitRequestAnimationFrame)
  4366. window.webkitRequestAnimationFrame(func);
  4367. else if (window.mozRequestAnimationFrame)
  4368. window.mozRequestAnimationFrame(func);
  4369. else if (window.oRequestAnimationFrame)
  4370. window.oRequestAnimationFrame(func);
  4371. else {
  4372. window.setTimeout(func, 16);
  4373. }
  4374. };
  4375. Tools.RequestFullscreen = function (element) {
  4376. if (element.requestFullscreen)
  4377. element.requestFullscreen();
  4378. else if (element.msRequestFullscreen)
  4379. element.msRequestFullscreen();
  4380. else if (element.webkitRequestFullscreen)
  4381. element.webkitRequestFullscreen();
  4382. else if (element.mozRequestFullScreen)
  4383. element.mozRequestFullScreen();
  4384. };
  4385. Tools.ExitFullscreen = function () {
  4386. if (document.exitFullscreen) {
  4387. document.exitFullscreen();
  4388. }
  4389. else if (document.mozCancelFullScreen) {
  4390. document.mozCancelFullScreen();
  4391. }
  4392. else if (document.webkitCancelFullScreen) {
  4393. document.webkitCancelFullScreen();
  4394. }
  4395. else if (document.msCancelFullScreen) {
  4396. document.msCancelFullScreen();
  4397. }
  4398. };
  4399. // External files
  4400. Tools.CleanUrl = function (url) {
  4401. url = url.replace(/#/mg, "%23");
  4402. return url;
  4403. };
  4404. Tools.LoadImage = function (url, onload, onerror, database) {
  4405. if (url instanceof ArrayBuffer) {
  4406. url = Tools.EncodeArrayBufferTobase64(url);
  4407. }
  4408. url = Tools.CleanUrl(url);
  4409. var img = new Image();
  4410. if (url.substr(0, 5) !== "data:") {
  4411. if (Tools.CorsBehavior) {
  4412. switch (typeof (Tools.CorsBehavior)) {
  4413. case "function":
  4414. var result = Tools.CorsBehavior(url);
  4415. if (result) {
  4416. img.crossOrigin = result;
  4417. }
  4418. break;
  4419. case "string":
  4420. default:
  4421. img.crossOrigin = Tools.CorsBehavior;
  4422. break;
  4423. }
  4424. }
  4425. }
  4426. img.onload = function () {
  4427. onload(img);
  4428. };
  4429. img.onerror = function (err) {
  4430. Tools.Error("Error while trying to load texture: " + url);
  4431. if (Tools.UseFallbackTexture) {
  4432. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4433. onload(img);
  4434. }
  4435. else {
  4436. onerror();
  4437. }
  4438. };
  4439. var noIndexedDB = function () {
  4440. img.src = url;
  4441. };
  4442. var loadFromIndexedDB = function () {
  4443. database.loadImageFromDB(url, img);
  4444. };
  4445. //ANY database to do!
  4446. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4447. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4448. }
  4449. else {
  4450. if (url.indexOf("file:") === -1) {
  4451. noIndexedDB();
  4452. }
  4453. else {
  4454. try {
  4455. var textureName = url.substring(5).toLowerCase();
  4456. var blobURL;
  4457. try {
  4458. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4459. }
  4460. catch (ex) {
  4461. // Chrome doesn't support oneTimeOnly parameter
  4462. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4463. }
  4464. img.src = blobURL;
  4465. }
  4466. catch (e) {
  4467. img.src = null;
  4468. }
  4469. }
  4470. }
  4471. return img;
  4472. };
  4473. //ANY
  4474. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4475. url = Tools.CleanUrl(url);
  4476. var noIndexedDB = function () {
  4477. var request = new XMLHttpRequest();
  4478. var loadUrl = Tools.BaseUrl + url;
  4479. request.open('GET', loadUrl, true);
  4480. if (useArrayBuffer) {
  4481. request.responseType = "arraybuffer";
  4482. }
  4483. request.onprogress = progressCallBack;
  4484. request.onreadystatechange = function () {
  4485. if (request.readyState === 4) {
  4486. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4487. callback(!useArrayBuffer ? request.responseText : request.response);
  4488. }
  4489. else {
  4490. if (onError) {
  4491. onError();
  4492. }
  4493. else {
  4494. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4495. }
  4496. }
  4497. }
  4498. };
  4499. request.send(null);
  4500. };
  4501. var loadFromIndexedDB = function () {
  4502. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4503. };
  4504. if (url.indexOf("file:") !== -1) {
  4505. var fileName = url.substring(5).toLowerCase();
  4506. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4507. }
  4508. else {
  4509. // Caching all files
  4510. if (database && database.enableSceneOffline) {
  4511. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4512. }
  4513. else {
  4514. noIndexedDB();
  4515. }
  4516. }
  4517. };
  4518. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4519. var reader = new FileReader();
  4520. reader.onload = function (e) {
  4521. //target doesn't have result from ts 1.3
  4522. callback(e.target['result']);
  4523. };
  4524. reader.onprogress = progressCallback;
  4525. reader.readAsDataURL(fileToLoad);
  4526. };
  4527. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4528. var reader = new FileReader();
  4529. reader.onerror = function (e) {
  4530. Tools.Log("Error while reading file: " + fileToLoad.name);
  4531. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4532. };
  4533. reader.onload = function (e) {
  4534. //target doesn't have result from ts 1.3
  4535. callback(e.target['result']);
  4536. };
  4537. reader.onprogress = progressCallBack;
  4538. if (!useArrayBuffer) {
  4539. // Asynchronous read
  4540. reader.readAsText(fileToLoad);
  4541. }
  4542. else {
  4543. reader.readAsArrayBuffer(fileToLoad);
  4544. }
  4545. };
  4546. //returns a downloadable url to a file content.
  4547. Tools.FileAsURL = function (content) {
  4548. var fileBlob = new Blob([content]);
  4549. var url = window.URL || window.webkitURL;
  4550. var link = url.createObjectURL(fileBlob);
  4551. return link;
  4552. };
  4553. // Misc.
  4554. Tools.Format = function (value, decimals) {
  4555. if (decimals === void 0) { decimals = 2; }
  4556. return value.toFixed(decimals);
  4557. };
  4558. Tools.CheckExtends = function (v, min, max) {
  4559. if (v.x < min.x)
  4560. min.x = v.x;
  4561. if (v.y < min.y)
  4562. min.y = v.y;
  4563. if (v.z < min.z)
  4564. min.z = v.z;
  4565. if (v.x > max.x)
  4566. max.x = v.x;
  4567. if (v.y > max.y)
  4568. max.y = v.y;
  4569. if (v.z > max.z)
  4570. max.z = v.z;
  4571. };
  4572. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4573. for (var prop in source) {
  4574. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4575. continue;
  4576. }
  4577. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4578. continue;
  4579. }
  4580. var sourceValue = source[prop];
  4581. var typeOfSourceValue = typeof sourceValue;
  4582. if (typeOfSourceValue === "function") {
  4583. continue;
  4584. }
  4585. if (typeOfSourceValue === "object") {
  4586. if (sourceValue instanceof Array) {
  4587. destination[prop] = [];
  4588. if (sourceValue.length > 0) {
  4589. if (typeof sourceValue[0] == "object") {
  4590. for (var index = 0; index < sourceValue.length; index++) {
  4591. var clonedValue = cloneValue(sourceValue[index], destination);
  4592. if (destination[prop].indexOf(clonedValue) === -1) {
  4593. destination[prop].push(clonedValue);
  4594. }
  4595. }
  4596. }
  4597. else {
  4598. destination[prop] = sourceValue.slice(0);
  4599. }
  4600. }
  4601. }
  4602. else {
  4603. destination[prop] = cloneValue(sourceValue, destination);
  4604. }
  4605. }
  4606. else {
  4607. destination[prop] = sourceValue;
  4608. }
  4609. }
  4610. };
  4611. Tools.IsEmpty = function (obj) {
  4612. for (var i in obj) {
  4613. return false;
  4614. }
  4615. return true;
  4616. };
  4617. Tools.RegisterTopRootEvents = function (events) {
  4618. for (var index = 0; index < events.length; index++) {
  4619. var event = events[index];
  4620. window.addEventListener(event.name, event.handler, false);
  4621. try {
  4622. if (window.parent) {
  4623. window.parent.addEventListener(event.name, event.handler, false);
  4624. }
  4625. }
  4626. catch (e) {
  4627. }
  4628. }
  4629. };
  4630. Tools.UnregisterTopRootEvents = function (events) {
  4631. for (var index = 0; index < events.length; index++) {
  4632. var event = events[index];
  4633. window.removeEventListener(event.name, event.handler);
  4634. try {
  4635. if (window.parent) {
  4636. window.parent.removeEventListener(event.name, event.handler);
  4637. }
  4638. }
  4639. catch (e) {
  4640. }
  4641. }
  4642. };
  4643. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4644. // Read the contents of the framebuffer
  4645. var numberOfChannelsByLine = width * 4;
  4646. var halfHeight = height / 2;
  4647. //Reading datas from WebGL
  4648. var data = engine.readPixels(0, 0, width, height);
  4649. //To flip image on Y axis.
  4650. for (var i = 0; i < halfHeight; i++) {
  4651. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4652. var currentCell = j + i * numberOfChannelsByLine;
  4653. var targetLine = height - i - 1;
  4654. var targetCell = j + targetLine * numberOfChannelsByLine;
  4655. var temp = data[currentCell];
  4656. data[currentCell] = data[targetCell];
  4657. data[targetCell] = temp;
  4658. }
  4659. }
  4660. // Create a 2D canvas to store the result
  4661. if (!screenshotCanvas) {
  4662. screenshotCanvas = document.createElement('canvas');
  4663. }
  4664. screenshotCanvas.width = width;
  4665. screenshotCanvas.height = height;
  4666. var context = screenshotCanvas.getContext('2d');
  4667. // Copy the pixels to a 2D canvas
  4668. var imageData = context.createImageData(width, height);
  4669. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4670. var castData = imageData.data;
  4671. castData.set(data);
  4672. context.putImageData(imageData, 0, 0);
  4673. var base64Image = screenshotCanvas.toDataURL();
  4674. if (successCallback) {
  4675. successCallback(base64Image);
  4676. }
  4677. else {
  4678. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4679. if (("download" in document.createElement("a"))) {
  4680. var a = window.document.createElement("a");
  4681. a.href = base64Image;
  4682. var date = new Date();
  4683. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4684. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4685. window.document.body.appendChild(a);
  4686. a.addEventListener("click", function () {
  4687. a.parentElement.removeChild(a);
  4688. });
  4689. a.click();
  4690. }
  4691. else {
  4692. var newWindow = window.open("");
  4693. var img = newWindow.document.createElement("img");
  4694. img.src = base64Image;
  4695. newWindow.document.body.appendChild(img);
  4696. }
  4697. }
  4698. };
  4699. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4700. var width;
  4701. var height;
  4702. //If a precision value is specified
  4703. if (size.precision) {
  4704. width = Math.round(engine.getRenderWidth() * size.precision);
  4705. height = Math.round(width / engine.getAspectRatio(camera));
  4706. size = { width: width, height: height };
  4707. }
  4708. else if (size.width && size.height) {
  4709. width = size.width;
  4710. height = size.height;
  4711. }
  4712. else if (size.width && !size.height) {
  4713. width = size.width;
  4714. height = Math.round(width / engine.getAspectRatio(camera));
  4715. size = { width: width, height: height };
  4716. }
  4717. else if (size.height && !size.width) {
  4718. height = size.height;
  4719. width = Math.round(height * engine.getAspectRatio(camera));
  4720. size = { width: width, height: height };
  4721. }
  4722. else if (!isNaN(size)) {
  4723. height = size;
  4724. width = size;
  4725. }
  4726. else {
  4727. Tools.Error("Invalid 'size' parameter !");
  4728. return;
  4729. }
  4730. var scene = camera.getScene();
  4731. var previousCamera = null;
  4732. if (scene.activeCamera !== camera) {
  4733. previousCamera = scene.activeCamera;
  4734. scene.activeCamera = camera;
  4735. }
  4736. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4737. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4738. texture.renderList = scene.meshes;
  4739. texture.onAfterRender = function () {
  4740. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4741. };
  4742. scene.incrementRenderId();
  4743. texture.render(true);
  4744. texture.dispose();
  4745. if (previousCamera) {
  4746. scene.activeCamera = previousCamera;
  4747. }
  4748. camera.getProjectionMatrix(true); // Force cache refresh;
  4749. };
  4750. // XHR response validator for local file scenario
  4751. Tools.ValidateXHRData = function (xhr, dataType) {
  4752. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4753. if (dataType === void 0) { dataType = 7; }
  4754. try {
  4755. if (dataType & 1) {
  4756. if (xhr.responseText && xhr.responseText.length > 0) {
  4757. return true;
  4758. }
  4759. else if (dataType === 1) {
  4760. return false;
  4761. }
  4762. }
  4763. if (dataType & 2) {
  4764. // Check header width and height since there is no "TGA" magic number
  4765. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4766. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4767. return true;
  4768. }
  4769. else if (dataType === 2) {
  4770. return false;
  4771. }
  4772. }
  4773. if (dataType & 4) {
  4774. // Check for the "DDS" magic number
  4775. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4776. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4777. return true;
  4778. }
  4779. else {
  4780. return false;
  4781. }
  4782. }
  4783. }
  4784. catch (e) {
  4785. }
  4786. return false;
  4787. };
  4788. Tools.getClassName = function (obj) {
  4789. var funcNameRegex = /function (.{1,})\(/;
  4790. var results = (funcNameRegex).exec((obj).constructor.toString());
  4791. return (results && results.length > 1) ? results[1] : "";
  4792. };
  4793. Object.defineProperty(Tools, "NoneLogLevel", {
  4794. get: function () {
  4795. return Tools._NoneLogLevel;
  4796. },
  4797. enumerable: true,
  4798. configurable: true
  4799. });
  4800. Object.defineProperty(Tools, "MessageLogLevel", {
  4801. get: function () {
  4802. return Tools._MessageLogLevel;
  4803. },
  4804. enumerable: true,
  4805. configurable: true
  4806. });
  4807. Object.defineProperty(Tools, "WarningLogLevel", {
  4808. get: function () {
  4809. return Tools._WarningLogLevel;
  4810. },
  4811. enumerable: true,
  4812. configurable: true
  4813. });
  4814. Object.defineProperty(Tools, "ErrorLogLevel", {
  4815. get: function () {
  4816. return Tools._ErrorLogLevel;
  4817. },
  4818. enumerable: true,
  4819. configurable: true
  4820. });
  4821. Object.defineProperty(Tools, "AllLogLevel", {
  4822. get: function () {
  4823. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4824. },
  4825. enumerable: true,
  4826. configurable: true
  4827. });
  4828. Tools._AddLogEntry = function (entry) {
  4829. Tools._LogCache = entry + Tools._LogCache;
  4830. if (Tools.OnNewCacheEntry) {
  4831. Tools.OnNewCacheEntry(entry);
  4832. }
  4833. };
  4834. Tools._FormatMessage = function (message) {
  4835. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4836. var date = new Date();
  4837. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4838. };
  4839. Tools._LogDisabled = function (message) {
  4840. // nothing to do
  4841. };
  4842. Tools._LogEnabled = function (message) {
  4843. var formattedMessage = Tools._FormatMessage(message);
  4844. console.log("BJS - " + formattedMessage);
  4845. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4846. Tools._AddLogEntry(entry);
  4847. };
  4848. Tools._WarnDisabled = function (message) {
  4849. // nothing to do
  4850. };
  4851. Tools._WarnEnabled = function (message) {
  4852. var formattedMessage = Tools._FormatMessage(message);
  4853. console.warn("BJS - " + formattedMessage);
  4854. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4855. Tools._AddLogEntry(entry);
  4856. };
  4857. Tools._ErrorDisabled = function (message) {
  4858. // nothing to do
  4859. };
  4860. Tools._ErrorEnabled = function (message) {
  4861. Tools.errorsCount++;
  4862. var formattedMessage = Tools._FormatMessage(message);
  4863. console.error("BJS - " + formattedMessage);
  4864. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4865. Tools._AddLogEntry(entry);
  4866. };
  4867. Object.defineProperty(Tools, "LogCache", {
  4868. get: function () {
  4869. return Tools._LogCache;
  4870. },
  4871. enumerable: true,
  4872. configurable: true
  4873. });
  4874. Tools.ClearLogCache = function () {
  4875. Tools._LogCache = "";
  4876. Tools.errorsCount = 0;
  4877. };
  4878. Object.defineProperty(Tools, "LogLevels", {
  4879. set: function (level) {
  4880. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4881. Tools.Log = Tools._LogEnabled;
  4882. }
  4883. else {
  4884. Tools.Log = Tools._LogDisabled;
  4885. }
  4886. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4887. Tools.Warn = Tools._WarnEnabled;
  4888. }
  4889. else {
  4890. Tools.Warn = Tools._WarnDisabled;
  4891. }
  4892. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4893. Tools.Error = Tools._ErrorEnabled;
  4894. }
  4895. else {
  4896. Tools.Error = Tools._ErrorDisabled;
  4897. }
  4898. },
  4899. enumerable: true,
  4900. configurable: true
  4901. });
  4902. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4903. get: function () {
  4904. return Tools._PerformanceNoneLogLevel;
  4905. },
  4906. enumerable: true,
  4907. configurable: true
  4908. });
  4909. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4910. get: function () {
  4911. return Tools._PerformanceUserMarkLogLevel;
  4912. },
  4913. enumerable: true,
  4914. configurable: true
  4915. });
  4916. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4917. get: function () {
  4918. return Tools._PerformanceConsoleLogLevel;
  4919. },
  4920. enumerable: true,
  4921. configurable: true
  4922. });
  4923. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4924. set: function (level) {
  4925. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4926. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4927. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4928. return;
  4929. }
  4930. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4931. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4932. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4933. return;
  4934. }
  4935. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4936. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4937. },
  4938. enumerable: true,
  4939. configurable: true
  4940. });
  4941. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4942. };
  4943. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4944. };
  4945. Tools._StartUserMark = function (counterName, condition) {
  4946. if (condition === void 0) { condition = true; }
  4947. if (!condition || !Tools._performance.mark) {
  4948. return;
  4949. }
  4950. Tools._performance.mark(counterName + "-Begin");
  4951. };
  4952. Tools._EndUserMark = function (counterName, condition) {
  4953. if (condition === void 0) { condition = true; }
  4954. if (!condition || !Tools._performance.mark) {
  4955. return;
  4956. }
  4957. Tools._performance.mark(counterName + "-End");
  4958. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4959. };
  4960. Tools._StartPerformanceConsole = function (counterName, condition) {
  4961. if (condition === void 0) { condition = true; }
  4962. if (!condition) {
  4963. return;
  4964. }
  4965. Tools._StartUserMark(counterName, condition);
  4966. if (console.time) {
  4967. console.time(counterName);
  4968. }
  4969. };
  4970. Tools._EndPerformanceConsole = function (counterName, condition) {
  4971. if (condition === void 0) { condition = true; }
  4972. if (!condition) {
  4973. return;
  4974. }
  4975. Tools._EndUserMark(counterName, condition);
  4976. if (console.time) {
  4977. console.timeEnd(counterName);
  4978. }
  4979. };
  4980. Object.defineProperty(Tools, "Now", {
  4981. get: function () {
  4982. if (window.performance && window.performance.now) {
  4983. return window.performance.now();
  4984. }
  4985. return new Date().getTime();
  4986. },
  4987. enumerable: true,
  4988. configurable: true
  4989. });
  4990. Tools.BaseUrl = "";
  4991. Tools.CorsBehavior = "anonymous";
  4992. Tools.UseFallbackTexture = true;
  4993. // Logs
  4994. Tools._NoneLogLevel = 0;
  4995. Tools._MessageLogLevel = 1;
  4996. Tools._WarningLogLevel = 2;
  4997. Tools._ErrorLogLevel = 4;
  4998. Tools._LogCache = "";
  4999. Tools.errorsCount = 0;
  5000. Tools.Log = Tools._LogEnabled;
  5001. Tools.Warn = Tools._WarnEnabled;
  5002. Tools.Error = Tools._ErrorEnabled;
  5003. // Performances
  5004. Tools._PerformanceNoneLogLevel = 0;
  5005. Tools._PerformanceUserMarkLogLevel = 1;
  5006. Tools._PerformanceConsoleLogLevel = 2;
  5007. Tools._performance = window.performance;
  5008. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5009. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5010. return Tools;
  5011. })();
  5012. BABYLON.Tools = Tools;
  5013. /**
  5014. * An implementation of a loop for asynchronous functions.
  5015. */
  5016. var AsyncLoop = (function () {
  5017. /**
  5018. * Constroctor.
  5019. * @param iterations the number of iterations.
  5020. * @param _fn the function to run each iteration
  5021. * @param _successCallback the callback that will be called upon succesful execution
  5022. * @param offset starting offset.
  5023. */
  5024. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5025. if (offset === void 0) { offset = 0; }
  5026. this.iterations = iterations;
  5027. this._fn = _fn;
  5028. this._successCallback = _successCallback;
  5029. this.index = offset - 1;
  5030. this._done = false;
  5031. }
  5032. /**
  5033. * Execute the next iteration. Must be called after the last iteration was finished.
  5034. */
  5035. AsyncLoop.prototype.executeNext = function () {
  5036. if (!this._done) {
  5037. if (this.index + 1 < this.iterations) {
  5038. ++this.index;
  5039. this._fn(this);
  5040. }
  5041. else {
  5042. this.breakLoop();
  5043. }
  5044. }
  5045. };
  5046. /**
  5047. * Break the loop and run the success callback.
  5048. */
  5049. AsyncLoop.prototype.breakLoop = function () {
  5050. this._done = true;
  5051. this._successCallback();
  5052. };
  5053. /**
  5054. * Helper function
  5055. */
  5056. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5057. if (offset === void 0) { offset = 0; }
  5058. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5059. loop.executeNext();
  5060. return loop;
  5061. };
  5062. /**
  5063. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5064. * @param iterations total number of iterations
  5065. * @param syncedIterations number of synchronous iterations in each async iteration.
  5066. * @param fn the function to call each iteration.
  5067. * @param callback a success call back that will be called when iterating stops.
  5068. * @param breakFunction a break condition (optional)
  5069. * @param timeout timeout settings for the setTimeout function. default - 0.
  5070. * @constructor
  5071. */
  5072. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5073. if (timeout === void 0) { timeout = 0; }
  5074. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5075. if (breakFunction && breakFunction())
  5076. loop.breakLoop();
  5077. else {
  5078. setTimeout(function () {
  5079. for (var i = 0; i < syncedIterations; ++i) {
  5080. var iteration = (loop.index * syncedIterations) + i;
  5081. if (iteration >= iterations)
  5082. break;
  5083. fn(iteration);
  5084. if (breakFunction && breakFunction()) {
  5085. loop.breakLoop();
  5086. break;
  5087. }
  5088. }
  5089. loop.executeNext();
  5090. }, timeout);
  5091. }
  5092. }, callback);
  5093. };
  5094. return AsyncLoop;
  5095. })();
  5096. BABYLON.AsyncLoop = AsyncLoop;
  5097. })(BABYLON || (BABYLON = {}));
  5098. var BABYLON;
  5099. (function (BABYLON) {
  5100. var Internals;
  5101. (function (Internals) {
  5102. var _AlphaState = (function () {
  5103. function _AlphaState() {
  5104. this._isAlphaBlendDirty = false;
  5105. this._isBlendFunctionParametersDirty = false;
  5106. this._alphaBlend = false;
  5107. this._blendFunctionParameters = new Array(4);
  5108. }
  5109. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5110. get: function () {
  5111. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5112. },
  5113. enumerable: true,
  5114. configurable: true
  5115. });
  5116. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5117. get: function () {
  5118. return this._alphaBlend;
  5119. },
  5120. set: function (value) {
  5121. if (this._alphaBlend === value) {
  5122. return;
  5123. }
  5124. this._alphaBlend = value;
  5125. this._isAlphaBlendDirty = true;
  5126. },
  5127. enumerable: true,
  5128. configurable: true
  5129. });
  5130. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5131. if (this._blendFunctionParameters[0] === value0 &&
  5132. this._blendFunctionParameters[1] === value1 &&
  5133. this._blendFunctionParameters[2] === value2 &&
  5134. this._blendFunctionParameters[3] === value3) {
  5135. return;
  5136. }
  5137. this._blendFunctionParameters[0] = value0;
  5138. this._blendFunctionParameters[1] = value1;
  5139. this._blendFunctionParameters[2] = value2;
  5140. this._blendFunctionParameters[3] = value3;
  5141. this._isBlendFunctionParametersDirty = true;
  5142. };
  5143. _AlphaState.prototype.reset = function () {
  5144. this._alphaBlend = false;
  5145. this._blendFunctionParameters[0] = null;
  5146. this._blendFunctionParameters[1] = null;
  5147. this._blendFunctionParameters[2] = null;
  5148. this._blendFunctionParameters[3] = null;
  5149. this._isAlphaBlendDirty = true;
  5150. this._isBlendFunctionParametersDirty = false;
  5151. };
  5152. _AlphaState.prototype.apply = function (gl) {
  5153. if (!this.isDirty) {
  5154. return;
  5155. }
  5156. // Alpha blend
  5157. if (this._isAlphaBlendDirty) {
  5158. if (this._alphaBlend) {
  5159. gl.enable(gl.BLEND);
  5160. }
  5161. else {
  5162. gl.disable(gl.BLEND);
  5163. }
  5164. this._isAlphaBlendDirty = false;
  5165. }
  5166. // Alpha function
  5167. if (this._isBlendFunctionParametersDirty) {
  5168. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5169. this._isBlendFunctionParametersDirty = false;
  5170. }
  5171. };
  5172. return _AlphaState;
  5173. })();
  5174. Internals._AlphaState = _AlphaState;
  5175. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5176. })(BABYLON || (BABYLON = {}));
  5177. var BABYLON;
  5178. (function (BABYLON) {
  5179. var Internals;
  5180. (function (Internals) {
  5181. var _DepthCullingState = (function () {
  5182. function _DepthCullingState() {
  5183. this._isDepthTestDirty = false;
  5184. this._isDepthMaskDirty = false;
  5185. this._isDepthFuncDirty = false;
  5186. this._isCullFaceDirty = false;
  5187. this._isCullDirty = false;
  5188. this._isZOffsetDirty = false;
  5189. }
  5190. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5191. get: function () {
  5192. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5193. },
  5194. enumerable: true,
  5195. configurable: true
  5196. });
  5197. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5198. get: function () {
  5199. return this._zOffset;
  5200. },
  5201. set: function (value) {
  5202. if (this._zOffset === value) {
  5203. return;
  5204. }
  5205. this._zOffset = value;
  5206. this._isZOffsetDirty = true;
  5207. },
  5208. enumerable: true,
  5209. configurable: true
  5210. });
  5211. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5212. get: function () {
  5213. return this._cullFace;
  5214. },
  5215. set: function (value) {
  5216. if (this._cullFace === value) {
  5217. return;
  5218. }
  5219. this._cullFace = value;
  5220. this._isCullFaceDirty = true;
  5221. },
  5222. enumerable: true,
  5223. configurable: true
  5224. });
  5225. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5226. get: function () {
  5227. return this._cull;
  5228. },
  5229. set: function (value) {
  5230. if (this._cull === value) {
  5231. return;
  5232. }
  5233. this._cull = value;
  5234. this._isCullDirty = true;
  5235. },
  5236. enumerable: true,
  5237. configurable: true
  5238. });
  5239. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5240. get: function () {
  5241. return this._depthFunc;
  5242. },
  5243. set: function (value) {
  5244. if (this._depthFunc === value) {
  5245. return;
  5246. }
  5247. this._depthFunc = value;
  5248. this._isDepthFuncDirty = true;
  5249. },
  5250. enumerable: true,
  5251. configurable: true
  5252. });
  5253. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5254. get: function () {
  5255. return this._depthMask;
  5256. },
  5257. set: function (value) {
  5258. if (this._depthMask === value) {
  5259. return;
  5260. }
  5261. this._depthMask = value;
  5262. this._isDepthMaskDirty = true;
  5263. },
  5264. enumerable: true,
  5265. configurable: true
  5266. });
  5267. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5268. get: function () {
  5269. return this._depthTest;
  5270. },
  5271. set: function (value) {
  5272. if (this._depthTest === value) {
  5273. return;
  5274. }
  5275. this._depthTest = value;
  5276. this._isDepthTestDirty = true;
  5277. },
  5278. enumerable: true,
  5279. configurable: true
  5280. });
  5281. _DepthCullingState.prototype.reset = function () {
  5282. this._depthMask = true;
  5283. this._depthTest = true;
  5284. this._depthFunc = null;
  5285. this._cull = null;
  5286. this._cullFace = null;
  5287. this._zOffset = 0;
  5288. this._isDepthTestDirty = true;
  5289. this._isDepthMaskDirty = true;
  5290. this._isDepthFuncDirty = false;
  5291. this._isCullFaceDirty = false;
  5292. this._isCullDirty = false;
  5293. this._isZOffsetDirty = false;
  5294. };
  5295. _DepthCullingState.prototype.apply = function (gl) {
  5296. if (!this.isDirty) {
  5297. return;
  5298. }
  5299. // Cull
  5300. if (this._isCullDirty) {
  5301. if (this.cull) {
  5302. gl.enable(gl.CULL_FACE);
  5303. }
  5304. else {
  5305. gl.disable(gl.CULL_FACE);
  5306. }
  5307. this._isCullDirty = false;
  5308. }
  5309. // Cull face
  5310. if (this._isCullFaceDirty) {
  5311. gl.cullFace(this.cullFace);
  5312. this._isCullFaceDirty = false;
  5313. }
  5314. // Depth mask
  5315. if (this._isDepthMaskDirty) {
  5316. gl.depthMask(this.depthMask);
  5317. this._isDepthMaskDirty = false;
  5318. }
  5319. // Depth test
  5320. if (this._isDepthTestDirty) {
  5321. if (this.depthTest) {
  5322. gl.enable(gl.DEPTH_TEST);
  5323. }
  5324. else {
  5325. gl.disable(gl.DEPTH_TEST);
  5326. }
  5327. this._isDepthTestDirty = false;
  5328. }
  5329. // Depth func
  5330. if (this._isDepthFuncDirty) {
  5331. gl.depthFunc(this.depthFunc);
  5332. this._isDepthFuncDirty = false;
  5333. }
  5334. // zOffset
  5335. if (this._isZOffsetDirty) {
  5336. if (this.zOffset) {
  5337. gl.enable(gl.POLYGON_OFFSET_FILL);
  5338. gl.polygonOffset(this.zOffset, 0);
  5339. }
  5340. else {
  5341. gl.disable(gl.POLYGON_OFFSET_FILL);
  5342. }
  5343. this._isZOffsetDirty = false;
  5344. }
  5345. };
  5346. return _DepthCullingState;
  5347. })();
  5348. Internals._DepthCullingState = _DepthCullingState;
  5349. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5350. })(BABYLON || (BABYLON = {}));
  5351. var BABYLON;
  5352. (function (BABYLON) {
  5353. var compileShader = function (gl, source, type, defines) {
  5354. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5355. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5356. gl.compileShader(shader);
  5357. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5358. throw new Error(gl.getShaderInfoLog(shader));
  5359. }
  5360. return shader;
  5361. };
  5362. var getWebGLTextureType = function (gl, type) {
  5363. var textureType = gl.UNSIGNED_BYTE;
  5364. if (type === Engine.TEXTURETYPE_FLOAT)
  5365. textureType = gl.FLOAT;
  5366. return textureType;
  5367. };
  5368. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5369. var magFilter = gl.NEAREST;
  5370. var minFilter = gl.NEAREST;
  5371. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5372. magFilter = gl.LINEAR;
  5373. if (generateMipMaps) {
  5374. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5375. }
  5376. else {
  5377. minFilter = gl.LINEAR;
  5378. }
  5379. }
  5380. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5381. magFilter = gl.LINEAR;
  5382. if (generateMipMaps) {
  5383. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5384. }
  5385. else {
  5386. minFilter = gl.LINEAR;
  5387. }
  5388. }
  5389. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5390. magFilter = gl.NEAREST;
  5391. if (generateMipMaps) {
  5392. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5393. }
  5394. else {
  5395. minFilter = gl.NEAREST;
  5396. }
  5397. }
  5398. return {
  5399. min: minFilter,
  5400. mag: magFilter
  5401. };
  5402. };
  5403. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5404. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5405. var engine = scene.getEngine();
  5406. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5407. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5408. gl.bindTexture(gl.TEXTURE_2D, texture);
  5409. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5410. texture._baseWidth = width;
  5411. texture._baseHeight = height;
  5412. texture._width = potWidth;
  5413. texture._height = potHeight;
  5414. texture.isReady = true;
  5415. processFunction(potWidth, potHeight);
  5416. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5418. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5419. if (!noMipmap && !isCompressed) {
  5420. gl.generateMipmap(gl.TEXTURE_2D);
  5421. }
  5422. gl.bindTexture(gl.TEXTURE_2D, null);
  5423. engine.resetTextureCache();
  5424. scene._removePendingData(texture);
  5425. if (onLoad) {
  5426. onLoad();
  5427. }
  5428. };
  5429. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5430. var img;
  5431. var onload = function () {
  5432. loadedImages[index] = img;
  5433. loadedImages._internalCount++;
  5434. scene._removePendingData(img);
  5435. if (loadedImages._internalCount === 6) {
  5436. onfinish(loadedImages);
  5437. }
  5438. };
  5439. var onerror = function () {
  5440. scene._removePendingData(img);
  5441. };
  5442. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5443. scene._addPendingData(img);
  5444. };
  5445. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5446. var loadedImages = [];
  5447. loadedImages._internalCount = 0;
  5448. for (var index = 0; index < 6; index++) {
  5449. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5450. }
  5451. };
  5452. var EngineCapabilities = (function () {
  5453. function EngineCapabilities() {
  5454. }
  5455. return EngineCapabilities;
  5456. })();
  5457. BABYLON.EngineCapabilities = EngineCapabilities;
  5458. /**
  5459. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5460. */
  5461. var Engine = (function () {
  5462. /**
  5463. * @constructor
  5464. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5465. * @param {boolean} [antialias] - enable antialias
  5466. * @param options - further options to be sent to the getContext function
  5467. */
  5468. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5469. var _this = this;
  5470. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5471. // Public members
  5472. this.isFullscreen = false;
  5473. this.isPointerLock = false;
  5474. this.cullBackFaces = true;
  5475. this.renderEvenInBackground = true;
  5476. // To enable/disable IDB support and avoid XHR on .manifest
  5477. this.enableOfflineSupport = true;
  5478. this.scenes = new Array();
  5479. this._windowIsBackground = false;
  5480. this._webGLVersion = "1.0";
  5481. this._drawCalls = 0;
  5482. this._renderingQueueLaunched = false;
  5483. this._activeRenderLoops = [];
  5484. // FPS
  5485. this.fpsRange = 60;
  5486. this.previousFramesDuration = [];
  5487. this.fps = 60;
  5488. this.deltaTime = 0;
  5489. // States
  5490. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5491. this._alphaState = new BABYLON.Internals._AlphaState();
  5492. this._alphaMode = Engine.ALPHA_DISABLE;
  5493. // Cache
  5494. this._loadedTexturesCache = new Array();
  5495. this._maxTextureChannels = 16;
  5496. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5497. this._compiledEffects = {};
  5498. this._uintIndicesCurrentlySet = false;
  5499. this._renderingCanvas = canvas;
  5500. options = options || {};
  5501. options.antialias = antialias;
  5502. if (options.preserveDrawingBuffer === undefined) {
  5503. options.preserveDrawingBuffer = false;
  5504. }
  5505. // GL
  5506. //try {
  5507. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5508. // if (this._gl) {
  5509. // this._webGLVersion = "2.0";
  5510. // }
  5511. //} catch (e) {
  5512. // // Do nothing
  5513. //}
  5514. if (!this._gl) {
  5515. try {
  5516. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5517. }
  5518. catch (e) {
  5519. throw new Error("WebGL not supported");
  5520. }
  5521. }
  5522. if (!this._gl) {
  5523. throw new Error("WebGL not supported");
  5524. }
  5525. this._onBlur = function () {
  5526. _this._windowIsBackground = true;
  5527. };
  5528. this._onFocus = function () {
  5529. _this._windowIsBackground = false;
  5530. };
  5531. window.addEventListener("blur", this._onBlur);
  5532. window.addEventListener("focus", this._onFocus);
  5533. // Viewport
  5534. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5535. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5536. this.resize();
  5537. // Caps
  5538. this._caps = new EngineCapabilities();
  5539. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5540. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5541. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5542. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5543. // Infos
  5544. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5545. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5546. if (rendererInfo != null) {
  5547. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5548. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5549. }
  5550. if (!this._glVendor) {
  5551. this._glVendor = "Unknown vendor";
  5552. }
  5553. if (!this._glRenderer) {
  5554. this._glRenderer = "Unknown renderer";
  5555. }
  5556. // Extensions
  5557. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5558. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5559. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5560. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  5561. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5562. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5563. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5564. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5565. this._caps.highPrecisionShaderSupported = true;
  5566. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5567. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5568. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5569. if (this._gl.getShaderPrecisionFormat) {
  5570. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5571. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5572. }
  5573. // Depth buffer
  5574. this.setDepthBuffer(true);
  5575. this.setDepthFunctionToLessOrEqual();
  5576. this.setDepthWrite(true);
  5577. // Fullscreen
  5578. this._onFullscreenChange = function () {
  5579. if (document.fullscreen !== undefined) {
  5580. _this.isFullscreen = document.fullscreen;
  5581. }
  5582. else if (document.mozFullScreen !== undefined) {
  5583. _this.isFullscreen = document.mozFullScreen;
  5584. }
  5585. else if (document.webkitIsFullScreen !== undefined) {
  5586. _this.isFullscreen = document.webkitIsFullScreen;
  5587. }
  5588. else if (document.msIsFullScreen !== undefined) {
  5589. _this.isFullscreen = document.msIsFullScreen;
  5590. }
  5591. // Pointer lock
  5592. if (_this.isFullscreen && _this._pointerLockRequested) {
  5593. canvas.requestPointerLock = canvas.requestPointerLock ||
  5594. canvas.msRequestPointerLock ||
  5595. canvas.mozRequestPointerLock ||
  5596. canvas.webkitRequestPointerLock;
  5597. if (canvas.requestPointerLock) {
  5598. canvas.requestPointerLock();
  5599. }
  5600. }
  5601. };
  5602. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5603. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5604. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5605. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5606. // Pointer lock
  5607. this._onPointerLockChange = function () {
  5608. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5609. document.webkitPointerLockElement === canvas ||
  5610. document.msPointerLockElement === canvas ||
  5611. document.pointerLockElement === canvas);
  5612. };
  5613. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5614. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5615. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5616. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5617. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5618. Engine.audioEngine = new BABYLON.AudioEngine();
  5619. }
  5620. //default loading screen
  5621. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5622. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5623. }
  5624. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5625. get: function () {
  5626. return Engine._ALPHA_DISABLE;
  5627. },
  5628. enumerable: true,
  5629. configurable: true
  5630. });
  5631. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5632. get: function () {
  5633. return Engine._ALPHA_ONEONE;
  5634. },
  5635. enumerable: true,
  5636. configurable: true
  5637. });
  5638. Object.defineProperty(Engine, "ALPHA_ADD", {
  5639. get: function () {
  5640. return Engine._ALPHA_ADD;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5646. get: function () {
  5647. return Engine._ALPHA_COMBINE;
  5648. },
  5649. enumerable: true,
  5650. configurable: true
  5651. });
  5652. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5653. get: function () {
  5654. return Engine._ALPHA_SUBTRACT;
  5655. },
  5656. enumerable: true,
  5657. configurable: true
  5658. });
  5659. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5660. get: function () {
  5661. return Engine._ALPHA_MULTIPLY;
  5662. },
  5663. enumerable: true,
  5664. configurable: true
  5665. });
  5666. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5667. get: function () {
  5668. return Engine._ALPHA_MAXIMIZED;
  5669. },
  5670. enumerable: true,
  5671. configurable: true
  5672. });
  5673. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5674. get: function () {
  5675. return Engine._DELAYLOADSTATE_NONE;
  5676. },
  5677. enumerable: true,
  5678. configurable: true
  5679. });
  5680. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5681. get: function () {
  5682. return Engine._DELAYLOADSTATE_LOADED;
  5683. },
  5684. enumerable: true,
  5685. configurable: true
  5686. });
  5687. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5688. get: function () {
  5689. return Engine._DELAYLOADSTATE_LOADING;
  5690. },
  5691. enumerable: true,
  5692. configurable: true
  5693. });
  5694. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5695. get: function () {
  5696. return Engine._DELAYLOADSTATE_NOTLOADED;
  5697. },
  5698. enumerable: true,
  5699. configurable: true
  5700. });
  5701. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5702. get: function () {
  5703. return Engine._TEXTUREFORMAT_ALPHA;
  5704. },
  5705. enumerable: true,
  5706. configurable: true
  5707. });
  5708. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5709. get: function () {
  5710. return Engine._TEXTUREFORMAT_LUMINANCE;
  5711. },
  5712. enumerable: true,
  5713. configurable: true
  5714. });
  5715. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5716. get: function () {
  5717. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5718. },
  5719. enumerable: true,
  5720. configurable: true
  5721. });
  5722. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5723. get: function () {
  5724. return Engine._TEXTUREFORMAT_RGB;
  5725. },
  5726. enumerable: true,
  5727. configurable: true
  5728. });
  5729. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5730. get: function () {
  5731. return Engine._TEXTUREFORMAT_RGBA;
  5732. },
  5733. enumerable: true,
  5734. configurable: true
  5735. });
  5736. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5737. get: function () {
  5738. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5739. },
  5740. enumerable: true,
  5741. configurable: true
  5742. });
  5743. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5744. get: function () {
  5745. return Engine._TEXTURETYPE_FLOAT;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. Object.defineProperty(Engine, "Version", {
  5751. get: function () {
  5752. return "2.4.0-alpha";
  5753. },
  5754. enumerable: true,
  5755. configurable: true
  5756. });
  5757. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5758. get: function () {
  5759. return this._webGLVersion;
  5760. },
  5761. enumerable: true,
  5762. configurable: true
  5763. });
  5764. Engine.prototype._prepareWorkingCanvas = function () {
  5765. if (this._workingCanvas) {
  5766. return;
  5767. }
  5768. this._workingCanvas = document.createElement("canvas");
  5769. this._workingContext = this._workingCanvas.getContext("2d");
  5770. };
  5771. Engine.prototype.resetTextureCache = function () {
  5772. for (var index = 0; index < this._maxTextureChannels; index++) {
  5773. this._activeTexturesCache[index] = null;
  5774. }
  5775. };
  5776. Engine.prototype.getGlInfo = function () {
  5777. return {
  5778. vendor: this._glVendor,
  5779. renderer: this._glRenderer,
  5780. version: this._glVersion
  5781. };
  5782. };
  5783. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5784. if (useScreen === void 0) { useScreen = false; }
  5785. var viewport = camera.viewport;
  5786. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5787. };
  5788. Engine.prototype.getRenderWidth = function (useScreen) {
  5789. if (useScreen === void 0) { useScreen = false; }
  5790. if (!useScreen && this._currentRenderTarget) {
  5791. return this._currentRenderTarget._width;
  5792. }
  5793. return this._renderingCanvas.width;
  5794. };
  5795. Engine.prototype.getRenderHeight = function (useScreen) {
  5796. if (useScreen === void 0) { useScreen = false; }
  5797. if (!useScreen && this._currentRenderTarget) {
  5798. return this._currentRenderTarget._height;
  5799. }
  5800. return this._renderingCanvas.height;
  5801. };
  5802. Engine.prototype.getRenderingCanvas = function () {
  5803. return this._renderingCanvas;
  5804. };
  5805. Engine.prototype.getRenderingCanvasClientRect = function () {
  5806. return this._renderingCanvas.getBoundingClientRect();
  5807. };
  5808. Engine.prototype.setHardwareScalingLevel = function (level) {
  5809. this._hardwareScalingLevel = level;
  5810. this.resize();
  5811. };
  5812. Engine.prototype.getHardwareScalingLevel = function () {
  5813. return this._hardwareScalingLevel;
  5814. };
  5815. Engine.prototype.getLoadedTexturesCache = function () {
  5816. return this._loadedTexturesCache;
  5817. };
  5818. Engine.prototype.getCaps = function () {
  5819. return this._caps;
  5820. };
  5821. Object.defineProperty(Engine.prototype, "drawCalls", {
  5822. get: function () {
  5823. return this._drawCalls;
  5824. },
  5825. enumerable: true,
  5826. configurable: true
  5827. });
  5828. // Methods
  5829. Engine.prototype.resetDrawCalls = function () {
  5830. this._drawCalls = 0;
  5831. };
  5832. Engine.prototype.setDepthFunctionToGreater = function () {
  5833. this._depthCullingState.depthFunc = this._gl.GREATER;
  5834. };
  5835. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5836. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5837. };
  5838. Engine.prototype.setDepthFunctionToLess = function () {
  5839. this._depthCullingState.depthFunc = this._gl.LESS;
  5840. };
  5841. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5842. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5843. };
  5844. /**
  5845. * stop executing a render loop function and remove it from the execution array
  5846. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5847. */
  5848. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5849. if (!renderFunction) {
  5850. this._activeRenderLoops = [];
  5851. return;
  5852. }
  5853. var index = this._activeRenderLoops.indexOf(renderFunction);
  5854. if (index >= 0) {
  5855. this._activeRenderLoops.splice(index, 1);
  5856. }
  5857. };
  5858. Engine.prototype._renderLoop = function () {
  5859. var shouldRender = true;
  5860. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5861. shouldRender = false;
  5862. }
  5863. if (shouldRender) {
  5864. // Start new frame
  5865. this.beginFrame();
  5866. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5867. var renderFunction = this._activeRenderLoops[index];
  5868. renderFunction();
  5869. }
  5870. // Present
  5871. this.endFrame();
  5872. }
  5873. if (this._activeRenderLoops.length > 0) {
  5874. // Register new frame
  5875. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5876. }
  5877. else {
  5878. this._renderingQueueLaunched = false;
  5879. }
  5880. };
  5881. /**
  5882. * Register and execute a render loop. The engine can have more than one render function.
  5883. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5884. * @example
  5885. * engine.runRenderLoop(function () {
  5886. * scene.render()
  5887. * })
  5888. */
  5889. Engine.prototype.runRenderLoop = function (renderFunction) {
  5890. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5891. return;
  5892. }
  5893. this._activeRenderLoops.push(renderFunction);
  5894. if (!this._renderingQueueLaunched) {
  5895. this._renderingQueueLaunched = true;
  5896. this._bindedRenderFunction = this._renderLoop.bind(this);
  5897. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5898. }
  5899. };
  5900. /**
  5901. * Toggle full screen mode.
  5902. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5903. */
  5904. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5905. if (this.isFullscreen) {
  5906. BABYLON.Tools.ExitFullscreen();
  5907. }
  5908. else {
  5909. this._pointerLockRequested = requestPointerLock;
  5910. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5911. }
  5912. };
  5913. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5914. this.applyStates();
  5915. if (backBuffer) {
  5916. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5917. }
  5918. if (depthStencil && this._depthCullingState.depthMask) {
  5919. this._gl.clearDepth(1.0);
  5920. }
  5921. var mode = 0;
  5922. if (backBuffer) {
  5923. mode |= this._gl.COLOR_BUFFER_BIT;
  5924. }
  5925. if (depthStencil && this._depthCullingState.depthMask) {
  5926. mode |= this._gl.DEPTH_BUFFER_BIT;
  5927. }
  5928. this._gl.clear(mode);
  5929. };
  5930. /**
  5931. * Set the WebGL's viewport
  5932. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5933. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5934. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5935. */
  5936. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5937. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5938. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5939. var x = viewport.x || 0;
  5940. var y = viewport.y || 0;
  5941. this._cachedViewport = viewport;
  5942. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5943. };
  5944. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5945. this._cachedViewport = null;
  5946. this._gl.viewport(x, y, width, height);
  5947. };
  5948. Engine.prototype.beginFrame = function () {
  5949. this._measureFps();
  5950. };
  5951. Engine.prototype.endFrame = function () {
  5952. //this.flushFramebuffer();
  5953. };
  5954. /**
  5955. * resize the view according to the canvas' size.
  5956. * @example
  5957. * window.addEventListener("resize", function () {
  5958. * engine.resize();
  5959. * });
  5960. */
  5961. Engine.prototype.resize = function () {
  5962. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5963. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5964. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5965. for (var index = 0; index < this.scenes.length; index++) {
  5966. var scene = this.scenes[index];
  5967. if (scene.debugLayer.isVisible()) {
  5968. scene.debugLayer._syncPositions();
  5969. }
  5970. }
  5971. };
  5972. /**
  5973. * force a specific size of the canvas
  5974. * @param {number} width - the new canvas' width
  5975. * @param {number} height - the new canvas' height
  5976. */
  5977. Engine.prototype.setSize = function (width, height) {
  5978. this._renderingCanvas.width = width;
  5979. this._renderingCanvas.height = height;
  5980. for (var index = 0; index < this.scenes.length; index++) {
  5981. var scene = this.scenes[index];
  5982. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5983. var cam = scene.cameras[camIndex];
  5984. cam._currentRenderId = 0;
  5985. }
  5986. }
  5987. };
  5988. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  5989. this._currentRenderTarget = texture;
  5990. var gl = this._gl;
  5991. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5992. if (texture.isCube) {
  5993. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5994. }
  5995. else {
  5996. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5997. }
  5998. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  5999. this.wipeCaches();
  6000. };
  6001. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6002. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6003. this._currentRenderTarget = null;
  6004. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6005. var gl = this._gl;
  6006. gl.bindTexture(gl.TEXTURE_2D, texture);
  6007. gl.generateMipmap(gl.TEXTURE_2D);
  6008. gl.bindTexture(gl.TEXTURE_2D, null);
  6009. }
  6010. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6011. };
  6012. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6013. if (texture.generateMipMaps) {
  6014. var gl = this._gl;
  6015. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6016. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6017. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6018. }
  6019. };
  6020. Engine.prototype.flushFramebuffer = function () {
  6021. this._gl.flush();
  6022. };
  6023. Engine.prototype.restoreDefaultFramebuffer = function () {
  6024. this._currentRenderTarget = null;
  6025. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6026. this.setViewport(this._cachedViewport);
  6027. this.wipeCaches();
  6028. };
  6029. // VBOs
  6030. Engine.prototype._resetVertexBufferBinding = function () {
  6031. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  6032. this._cachedVertexBuffers = null;
  6033. };
  6034. Engine.prototype.createVertexBuffer = function (vertices) {
  6035. var vbo = this._gl.createBuffer();
  6036. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6037. if (vertices instanceof Float32Array) {
  6038. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6039. }
  6040. else {
  6041. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6042. }
  6043. this._resetVertexBufferBinding();
  6044. vbo.references = 1;
  6045. return vbo;
  6046. };
  6047. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6048. var vbo = this._gl.createBuffer();
  6049. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6050. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6051. this._resetVertexBufferBinding();
  6052. vbo.references = 1;
  6053. return vbo;
  6054. };
  6055. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6056. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6057. if (offset === undefined) {
  6058. offset = 0;
  6059. }
  6060. if (vertices instanceof Float32Array) {
  6061. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6062. }
  6063. else {
  6064. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6065. }
  6066. this._resetVertexBufferBinding();
  6067. };
  6068. Engine.prototype._resetIndexBufferBinding = function () {
  6069. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6070. this._cachedIndexBuffer = null;
  6071. };
  6072. Engine.prototype.createIndexBuffer = function (indices) {
  6073. var vbo = this._gl.createBuffer();
  6074. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6075. // Check for 32 bits indices
  6076. var arrayBuffer;
  6077. var need32Bits = false;
  6078. if (this._caps.uintIndices) {
  6079. for (var index = 0; index < indices.length; index++) {
  6080. if (indices[index] > 65535) {
  6081. need32Bits = true;
  6082. break;
  6083. }
  6084. }
  6085. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6086. }
  6087. else {
  6088. arrayBuffer = new Uint16Array(indices);
  6089. }
  6090. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6091. this._resetIndexBufferBinding();
  6092. vbo.references = 1;
  6093. vbo.is32Bits = need32Bits;
  6094. return vbo;
  6095. };
  6096. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6097. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6098. this._cachedVertexBuffers = vertexBuffer;
  6099. this._cachedEffectForVertexBuffers = effect;
  6100. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6101. var offset = 0;
  6102. for (var index = 0; index < vertexDeclaration.length; index++) {
  6103. var order = effect.getAttributeLocation(index);
  6104. if (order >= 0) {
  6105. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6106. }
  6107. offset += vertexDeclaration[index] * 4;
  6108. }
  6109. }
  6110. if (this._cachedIndexBuffer !== indexBuffer) {
  6111. this._cachedIndexBuffer = indexBuffer;
  6112. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6113. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6114. }
  6115. };
  6116. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6117. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6118. this._cachedVertexBuffers = vertexBuffers;
  6119. this._cachedEffectForVertexBuffers = effect;
  6120. var attributes = effect.getAttributesNames();
  6121. for (var index = 0; index < attributes.length; index++) {
  6122. var order = effect.getAttributeLocation(index);
  6123. if (order >= 0) {
  6124. var vertexBuffer = vertexBuffers[attributes[index]];
  6125. if (!vertexBuffer) {
  6126. continue;
  6127. }
  6128. var stride = vertexBuffer.getStrideSize();
  6129. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6130. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6131. }
  6132. }
  6133. }
  6134. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6135. this._cachedIndexBuffer = indexBuffer;
  6136. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6137. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6138. }
  6139. };
  6140. Engine.prototype._releaseBuffer = function (buffer) {
  6141. buffer.references--;
  6142. if (buffer.references === 0) {
  6143. this._gl.deleteBuffer(buffer);
  6144. return true;
  6145. }
  6146. return false;
  6147. };
  6148. Engine.prototype.createInstancesBuffer = function (capacity) {
  6149. var buffer = this._gl.createBuffer();
  6150. buffer.capacity = capacity;
  6151. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6152. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6153. return buffer;
  6154. };
  6155. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6156. this._gl.deleteBuffer(buffer);
  6157. };
  6158. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6159. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6160. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6161. for (var index = 0; index < 4; index++) {
  6162. var offsetLocation = offsetLocations[index];
  6163. this._gl.enableVertexAttribArray(offsetLocation);
  6164. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6165. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6166. }
  6167. };
  6168. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6169. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6170. for (var index = 0; index < 4; index++) {
  6171. var offsetLocation = offsetLocations[index];
  6172. this._gl.disableVertexAttribArray(offsetLocation);
  6173. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6174. }
  6175. };
  6176. Engine.prototype.applyStates = function () {
  6177. this._depthCullingState.apply(this._gl);
  6178. this._alphaState.apply(this._gl);
  6179. };
  6180. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6181. // Apply states
  6182. this.applyStates();
  6183. this._drawCalls++;
  6184. // Render
  6185. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6186. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6187. if (instancesCount) {
  6188. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6189. return;
  6190. }
  6191. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6192. };
  6193. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6194. // Apply states
  6195. this.applyStates();
  6196. this._drawCalls++;
  6197. if (instancesCount) {
  6198. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6199. return;
  6200. }
  6201. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6202. };
  6203. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6204. // Apply states
  6205. this.applyStates();
  6206. this._drawCalls++;
  6207. if (instancesCount) {
  6208. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6209. return;
  6210. }
  6211. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6212. };
  6213. // Shaders
  6214. Engine.prototype._releaseEffect = function (effect) {
  6215. if (this._compiledEffects[effect._key]) {
  6216. delete this._compiledEffects[effect._key];
  6217. if (effect.getProgram()) {
  6218. this._gl.deleteProgram(effect.getProgram());
  6219. }
  6220. }
  6221. };
  6222. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6223. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6224. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6225. var name = vertex + "+" + fragment + "@" + defines;
  6226. if (this._compiledEffects[name]) {
  6227. return this._compiledEffects[name];
  6228. }
  6229. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6230. effect._key = name;
  6231. this._compiledEffects[name] = effect;
  6232. return effect;
  6233. };
  6234. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6235. if (uniformsNames === void 0) { uniformsNames = []; }
  6236. if (samplers === void 0) { samplers = []; }
  6237. if (defines === void 0) { defines = ""; }
  6238. return this.createEffect({
  6239. vertex: "particles",
  6240. fragmentElement: fragmentName
  6241. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6242. };
  6243. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6244. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6245. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6246. var shaderProgram = this._gl.createProgram();
  6247. this._gl.attachShader(shaderProgram, vertexShader);
  6248. this._gl.attachShader(shaderProgram, fragmentShader);
  6249. this._gl.linkProgram(shaderProgram);
  6250. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6251. if (!linked) {
  6252. var error = this._gl.getProgramInfoLog(shaderProgram);
  6253. if (error) {
  6254. throw new Error(error);
  6255. }
  6256. }
  6257. this._gl.deleteShader(vertexShader);
  6258. this._gl.deleteShader(fragmentShader);
  6259. return shaderProgram;
  6260. };
  6261. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6262. var results = [];
  6263. for (var index = 0; index < uniformsNames.length; index++) {
  6264. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6265. }
  6266. return results;
  6267. };
  6268. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6269. var results = [];
  6270. for (var index = 0; index < attributesNames.length; index++) {
  6271. try {
  6272. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6273. }
  6274. catch (e) {
  6275. results.push(-1);
  6276. }
  6277. }
  6278. return results;
  6279. };
  6280. Engine.prototype.enableEffect = function (effect) {
  6281. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6282. if (effect && effect.onBind) {
  6283. effect.onBind(effect);
  6284. }
  6285. return;
  6286. }
  6287. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6288. // Use program
  6289. this._gl.useProgram(effect.getProgram());
  6290. for (var i in this._vertexAttribArrays) {
  6291. //make sure this is a number)
  6292. var iAsNumber = +i;
  6293. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6294. continue;
  6295. }
  6296. this._vertexAttribArrays[iAsNumber] = false;
  6297. this._gl.disableVertexAttribArray(iAsNumber);
  6298. }
  6299. var attributesCount = effect.getAttributesCount();
  6300. for (var index = 0; index < attributesCount; index++) {
  6301. // Attributes
  6302. var order = effect.getAttributeLocation(index);
  6303. if (order >= 0) {
  6304. this._vertexAttribArrays[order] = true;
  6305. this._gl.enableVertexAttribArray(order);
  6306. }
  6307. }
  6308. this._currentEffect = effect;
  6309. if (effect.onBind) {
  6310. effect.onBind(effect);
  6311. }
  6312. };
  6313. Engine.prototype.setArray = function (uniform, array) {
  6314. if (!uniform)
  6315. return;
  6316. this._gl.uniform1fv(uniform, array);
  6317. };
  6318. Engine.prototype.setArray2 = function (uniform, array) {
  6319. if (!uniform || array.length % 2 !== 0)
  6320. return;
  6321. this._gl.uniform2fv(uniform, array);
  6322. };
  6323. Engine.prototype.setArray3 = function (uniform, array) {
  6324. if (!uniform || array.length % 3 !== 0)
  6325. return;
  6326. this._gl.uniform3fv(uniform, array);
  6327. };
  6328. Engine.prototype.setArray4 = function (uniform, array) {
  6329. if (!uniform || array.length % 4 !== 0)
  6330. return;
  6331. this._gl.uniform4fv(uniform, array);
  6332. };
  6333. Engine.prototype.setMatrices = function (uniform, matrices) {
  6334. if (!uniform)
  6335. return;
  6336. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6337. };
  6338. Engine.prototype.setMatrix = function (uniform, matrix) {
  6339. if (!uniform)
  6340. return;
  6341. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6342. };
  6343. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6344. if (!uniform)
  6345. return;
  6346. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6347. };
  6348. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6349. if (!uniform)
  6350. return;
  6351. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6352. };
  6353. Engine.prototype.setFloat = function (uniform, value) {
  6354. if (!uniform)
  6355. return;
  6356. this._gl.uniform1f(uniform, value);
  6357. };
  6358. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6359. if (!uniform)
  6360. return;
  6361. this._gl.uniform2f(uniform, x, y);
  6362. };
  6363. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6364. if (!uniform)
  6365. return;
  6366. this._gl.uniform3f(uniform, x, y, z);
  6367. };
  6368. Engine.prototype.setBool = function (uniform, bool) {
  6369. if (!uniform)
  6370. return;
  6371. this._gl.uniform1i(uniform, bool);
  6372. };
  6373. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6374. if (!uniform)
  6375. return;
  6376. this._gl.uniform4f(uniform, x, y, z, w);
  6377. };
  6378. Engine.prototype.setColor3 = function (uniform, color3) {
  6379. if (!uniform)
  6380. return;
  6381. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6382. };
  6383. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6384. if (!uniform)
  6385. return;
  6386. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6387. };
  6388. // States
  6389. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6390. if (zOffset === void 0) { zOffset = 0; }
  6391. if (reverseSide === void 0) { reverseSide = false; }
  6392. // Culling
  6393. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6394. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6395. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6396. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6397. if (culling) {
  6398. this._depthCullingState.cullFace = cullFace;
  6399. this._depthCullingState.cull = true;
  6400. }
  6401. else {
  6402. this._depthCullingState.cull = false;
  6403. }
  6404. }
  6405. // Z offset
  6406. this._depthCullingState.zOffset = zOffset;
  6407. };
  6408. Engine.prototype.setDepthBuffer = function (enable) {
  6409. this._depthCullingState.depthTest = enable;
  6410. };
  6411. Engine.prototype.getDepthWrite = function () {
  6412. return this._depthCullingState.depthMask;
  6413. };
  6414. Engine.prototype.setDepthWrite = function (enable) {
  6415. this._depthCullingState.depthMask = enable;
  6416. };
  6417. Engine.prototype.setColorWrite = function (enable) {
  6418. this._gl.colorMask(enable, enable, enable, enable);
  6419. };
  6420. Engine.prototype.setAlphaMode = function (mode) {
  6421. if (this._alphaMode === mode) {
  6422. return;
  6423. }
  6424. switch (mode) {
  6425. case Engine.ALPHA_DISABLE:
  6426. this.setDepthWrite(true);
  6427. this._alphaState.alphaBlend = false;
  6428. break;
  6429. case Engine.ALPHA_COMBINE:
  6430. this.setDepthWrite(false);
  6431. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6432. this._alphaState.alphaBlend = true;
  6433. break;
  6434. case Engine.ALPHA_ONEONE:
  6435. this.setDepthWrite(false);
  6436. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6437. this._alphaState.alphaBlend = true;
  6438. break;
  6439. case Engine.ALPHA_ADD:
  6440. this.setDepthWrite(false);
  6441. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6442. this._alphaState.alphaBlend = true;
  6443. break;
  6444. case Engine.ALPHA_SUBTRACT:
  6445. this.setDepthWrite(false);
  6446. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6447. this._alphaState.alphaBlend = true;
  6448. break;
  6449. case Engine.ALPHA_MULTIPLY:
  6450. this.setDepthWrite(false);
  6451. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6452. this._alphaState.alphaBlend = true;
  6453. break;
  6454. case Engine.ALPHA_MAXIMIZED:
  6455. this.setDepthWrite(false);
  6456. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6457. this._alphaState.alphaBlend = true;
  6458. break;
  6459. }
  6460. this._alphaMode = mode;
  6461. };
  6462. Engine.prototype.getAlphaMode = function () {
  6463. return this._alphaMode;
  6464. };
  6465. Engine.prototype.setAlphaTesting = function (enable) {
  6466. this._alphaTest = enable;
  6467. };
  6468. Engine.prototype.getAlphaTesting = function () {
  6469. return this._alphaTest;
  6470. };
  6471. // Textures
  6472. Engine.prototype.wipeCaches = function () {
  6473. this.resetTextureCache();
  6474. this._currentEffect = null;
  6475. this._depthCullingState.reset();
  6476. this._alphaState.reset();
  6477. this._cachedVertexBuffers = null;
  6478. this._cachedIndexBuffer = null;
  6479. this._cachedEffectForVertexBuffers = null;
  6480. };
  6481. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6482. var gl = this._gl;
  6483. gl.bindTexture(gl.TEXTURE_2D, texture);
  6484. var magFilter = gl.NEAREST;
  6485. var minFilter = gl.NEAREST;
  6486. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6487. magFilter = gl.LINEAR;
  6488. minFilter = gl.LINEAR;
  6489. }
  6490. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6491. magFilter = gl.LINEAR;
  6492. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6493. }
  6494. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6495. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6496. gl.bindTexture(gl.TEXTURE_2D, null);
  6497. texture.samplingMode = samplingMode;
  6498. };
  6499. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6500. var _this = this;
  6501. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6502. if (onLoad === void 0) { onLoad = null; }
  6503. if (onError === void 0) { onError = null; }
  6504. if (buffer === void 0) { buffer = null; }
  6505. var texture = this._gl.createTexture();
  6506. var extension;
  6507. var fromData = false;
  6508. if (url.substr(0, 5) === "data:") {
  6509. fromData = true;
  6510. }
  6511. if (!fromData)
  6512. extension = url.substr(url.length - 4, 4).toLowerCase();
  6513. else {
  6514. var oldUrl = url;
  6515. fromData = oldUrl.split(':');
  6516. url = oldUrl;
  6517. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6518. }
  6519. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6520. var isTGA = (extension === ".tga");
  6521. scene._addPendingData(texture);
  6522. texture.url = url;
  6523. texture.noMipmap = noMipmap;
  6524. texture.references = 1;
  6525. texture.samplingMode = samplingMode;
  6526. this._loadedTexturesCache.push(texture);
  6527. var onerror = function () {
  6528. scene._removePendingData(texture);
  6529. if (onError) {
  6530. onError();
  6531. }
  6532. };
  6533. var callback;
  6534. if (isTGA) {
  6535. callback = function (arrayBuffer) {
  6536. var data = new Uint8Array(arrayBuffer);
  6537. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6538. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6539. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6540. }, onLoad, samplingMode);
  6541. };
  6542. if (!(fromData instanceof Array))
  6543. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6544. callback(arrayBuffer);
  6545. }, onerror, scene.database, true);
  6546. else
  6547. callback(buffer);
  6548. }
  6549. else if (isDDS) {
  6550. callback = function (data) {
  6551. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6552. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6553. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6554. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6555. }, onLoad, samplingMode);
  6556. };
  6557. if (!(fromData instanceof Array))
  6558. BABYLON.Tools.LoadFile(url, function (data) {
  6559. callback(data);
  6560. }, onerror, scene.database, true);
  6561. else
  6562. callback(buffer);
  6563. }
  6564. else {
  6565. var onload = function (img) {
  6566. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6567. var isPot = (img.width === potWidth && img.height === potHeight);
  6568. if (!isPot) {
  6569. _this._prepareWorkingCanvas();
  6570. _this._workingCanvas.width = potWidth;
  6571. _this._workingCanvas.height = potHeight;
  6572. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6573. _this._workingContext.imageSmoothingEnabled = false;
  6574. _this._workingContext.mozImageSmoothingEnabled = false;
  6575. _this._workingContext.oImageSmoothingEnabled = false;
  6576. _this._workingContext.webkitImageSmoothingEnabled = false;
  6577. _this._workingContext.msImageSmoothingEnabled = false;
  6578. }
  6579. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6580. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6581. _this._workingContext.imageSmoothingEnabled = true;
  6582. _this._workingContext.mozImageSmoothingEnabled = true;
  6583. _this._workingContext.oImageSmoothingEnabled = true;
  6584. _this._workingContext.webkitImageSmoothingEnabled = true;
  6585. _this._workingContext.msImageSmoothingEnabled = true;
  6586. }
  6587. }
  6588. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6589. }, onLoad, samplingMode);
  6590. };
  6591. if (!(fromData instanceof Array))
  6592. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6593. else
  6594. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6595. }
  6596. return texture;
  6597. };
  6598. Engine.prototype._getInternalFormat = function (format) {
  6599. var internalFormat = this._gl.RGBA;
  6600. switch (format) {
  6601. case Engine.TEXTUREFORMAT_ALPHA:
  6602. internalFormat = this._gl.ALPHA;
  6603. break;
  6604. case Engine.TEXTUREFORMAT_LUMINANCE:
  6605. internalFormat = this._gl.LUMINANCE;
  6606. break;
  6607. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6608. internalFormat = this._gl.LUMINANCE_ALPHA;
  6609. break;
  6610. case Engine.TEXTUREFORMAT_RGB:
  6611. internalFormat = this._gl.RGB;
  6612. break;
  6613. case Engine.TEXTUREFORMAT_RGBA:
  6614. internalFormat = this._gl.RGBA;
  6615. break;
  6616. }
  6617. return internalFormat;
  6618. };
  6619. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6620. if (compression === void 0) { compression = null; }
  6621. var internalFormat = this._getInternalFormat(format);
  6622. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6623. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6624. if (compression) {
  6625. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6626. }
  6627. else {
  6628. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6629. }
  6630. if (texture.generateMipMaps) {
  6631. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6632. }
  6633. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6634. this.resetTextureCache();
  6635. texture.isReady = true;
  6636. };
  6637. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6638. if (compression === void 0) { compression = null; }
  6639. var texture = this._gl.createTexture();
  6640. texture._baseWidth = width;
  6641. texture._baseHeight = height;
  6642. texture._width = width;
  6643. texture._height = height;
  6644. texture.references = 1;
  6645. this.updateRawTexture(texture, data, format, invertY, compression);
  6646. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6647. // Filters
  6648. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6649. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6650. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6651. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6652. texture.samplingMode = samplingMode;
  6653. this._loadedTexturesCache.push(texture);
  6654. return texture;
  6655. };
  6656. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6657. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6658. var texture = this._gl.createTexture();
  6659. texture._baseWidth = width;
  6660. texture._baseHeight = height;
  6661. if (forceExponantOfTwo) {
  6662. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6663. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6664. }
  6665. this.resetTextureCache();
  6666. texture._width = width;
  6667. texture._height = height;
  6668. texture.isReady = false;
  6669. texture.generateMipMaps = generateMipMaps;
  6670. texture.references = 1;
  6671. texture.samplingMode = samplingMode;
  6672. this.updateTextureSamplingMode(samplingMode, texture);
  6673. this._loadedTexturesCache.push(texture);
  6674. return texture;
  6675. };
  6676. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6677. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6678. if (texture.isCube) {
  6679. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6680. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6681. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6682. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6683. }
  6684. else {
  6685. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6686. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6687. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6688. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6689. }
  6690. };
  6691. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6692. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6693. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6694. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6695. if (texture.generateMipMaps) {
  6696. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6697. }
  6698. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6699. this.resetTextureCache();
  6700. texture.isReady = true;
  6701. };
  6702. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6703. if (texture._isDisabled) {
  6704. return;
  6705. }
  6706. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6707. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6708. try {
  6709. // Testing video texture support
  6710. if (this._videoTextureSupported === undefined) {
  6711. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6712. if (this._gl.getError() !== 0) {
  6713. this._videoTextureSupported = false;
  6714. }
  6715. else {
  6716. this._videoTextureSupported = true;
  6717. }
  6718. }
  6719. // Copy video through the current working canvas if video texture is not supported
  6720. if (!this._videoTextureSupported) {
  6721. if (!texture._workingCanvas) {
  6722. texture._workingCanvas = document.createElement("canvas");
  6723. texture._workingContext = texture._workingCanvas.getContext("2d");
  6724. texture._workingCanvas.width = texture._width;
  6725. texture._workingCanvas.height = texture._height;
  6726. }
  6727. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6728. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6729. }
  6730. else {
  6731. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6732. }
  6733. if (texture.generateMipMaps) {
  6734. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6735. }
  6736. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6737. this.resetTextureCache();
  6738. texture.isReady = true;
  6739. }
  6740. catch (ex) {
  6741. // Something unexpected
  6742. // Let's disable the texture
  6743. texture._isDisabled = true;
  6744. }
  6745. };
  6746. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6747. // old version had a "generateMipMaps" arg instead of options.
  6748. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6749. // in the same way, generateDepthBuffer is defaulted to true
  6750. var generateMipMaps = false;
  6751. var generateDepthBuffer = true;
  6752. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6753. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6754. if (options !== undefined) {
  6755. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6756. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6757. type = options.type === undefined ? type : options.type;
  6758. if (options.samplingMode !== undefined) {
  6759. samplingMode = options.samplingMode;
  6760. }
  6761. if (type === Engine.TEXTURETYPE_FLOAT) {
  6762. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6763. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6764. }
  6765. }
  6766. var gl = this._gl;
  6767. var texture = gl.createTexture();
  6768. gl.bindTexture(gl.TEXTURE_2D, texture);
  6769. var width = size.width || size;
  6770. var height = size.height || size;
  6771. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6772. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6773. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6774. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6775. }
  6776. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6780. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6781. var depthBuffer;
  6782. // Create the depth buffer
  6783. if (generateDepthBuffer) {
  6784. depthBuffer = gl.createRenderbuffer();
  6785. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6786. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6787. }
  6788. // Create the framebuffer
  6789. var framebuffer = gl.createFramebuffer();
  6790. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6791. if (generateDepthBuffer) {
  6792. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6793. }
  6794. if (generateMipMaps) {
  6795. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6796. }
  6797. // Unbind
  6798. gl.bindTexture(gl.TEXTURE_2D, null);
  6799. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6800. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6801. texture._framebuffer = framebuffer;
  6802. if (generateDepthBuffer) {
  6803. texture._depthBuffer = depthBuffer;
  6804. }
  6805. texture._width = width;
  6806. texture._height = height;
  6807. texture.isReady = true;
  6808. texture.generateMipMaps = generateMipMaps;
  6809. texture.references = 1;
  6810. texture.samplingMode = samplingMode;
  6811. this.resetTextureCache();
  6812. this._loadedTexturesCache.push(texture);
  6813. return texture;
  6814. };
  6815. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6816. var gl = this._gl;
  6817. var texture = gl.createTexture();
  6818. var generateMipMaps = true;
  6819. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6820. if (options !== undefined) {
  6821. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6822. if (options.samplingMode !== undefined) {
  6823. samplingMode = options.samplingMode;
  6824. }
  6825. }
  6826. texture.isCube = true;
  6827. texture.references = 1;
  6828. texture.generateMipMaps = generateMipMaps;
  6829. texture.references = 1;
  6830. texture.samplingMode = samplingMode;
  6831. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6832. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6833. for (var face = 0; face < 6; face++) {
  6834. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6835. }
  6836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6838. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6839. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6840. // Create the depth buffer
  6841. var depthBuffer = gl.createRenderbuffer();
  6842. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6843. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6844. // Create the framebuffer
  6845. var framebuffer = gl.createFramebuffer();
  6846. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6847. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6848. // Mipmaps
  6849. if (texture.generateMipMaps) {
  6850. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6851. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6852. }
  6853. // Unbind
  6854. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6855. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6856. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6857. texture._framebuffer = framebuffer;
  6858. texture._depthBuffer = depthBuffer;
  6859. this.resetTextureCache();
  6860. texture._width = size;
  6861. texture._height = size;
  6862. texture.isReady = true;
  6863. return texture;
  6864. };
  6865. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6866. var _this = this;
  6867. var gl = this._gl;
  6868. var texture = gl.createTexture();
  6869. texture.isCube = true;
  6870. texture.url = rootUrl;
  6871. texture.references = 1;
  6872. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6873. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6874. if (isDDS) {
  6875. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6876. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6877. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6878. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6879. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6880. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6881. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6882. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6883. }
  6884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6887. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6888. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6889. _this.resetTextureCache();
  6890. texture._width = info.width;
  6891. texture._height = info.height;
  6892. texture.isReady = true;
  6893. }, null, null, true);
  6894. }
  6895. else {
  6896. cascadeLoad(rootUrl, scene, function (imgs) {
  6897. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6898. var height = width;
  6899. _this._prepareWorkingCanvas();
  6900. _this._workingCanvas.width = width;
  6901. _this._workingCanvas.height = height;
  6902. var faces = [
  6903. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6904. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6905. ];
  6906. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6907. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6908. for (var index = 0; index < faces.length; index++) {
  6909. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6910. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6911. }
  6912. if (!noMipmap) {
  6913. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6914. }
  6915. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6917. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6918. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6919. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6920. _this.resetTextureCache();
  6921. texture._width = width;
  6922. texture._height = height;
  6923. texture.isReady = true;
  6924. }, files);
  6925. }
  6926. return texture;
  6927. };
  6928. Engine.prototype.updateTextureSize = function (texture, width, height) {
  6929. texture._width = width;
  6930. texture._height = height;
  6931. };
  6932. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6933. var _this = this;
  6934. var gl = this._gl;
  6935. var texture = gl.createTexture();
  6936. scene._addPendingData(texture);
  6937. texture.isCube = true;
  6938. texture.references = 1;
  6939. texture.url = url;
  6940. var internalFormat = this._getInternalFormat(format);
  6941. var textureType = gl.UNSIGNED_BYTE;
  6942. if (type === Engine.TEXTURETYPE_FLOAT) {
  6943. textureType = gl.FLOAT;
  6944. }
  6945. var width = size;
  6946. var height = width;
  6947. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6948. texture._width = width;
  6949. texture._height = height;
  6950. var onerror = function () {
  6951. scene._removePendingData(texture);
  6952. };
  6953. var internalCallback = function (data) {
  6954. var rgbeDataArrays = callback(data);
  6955. var facesIndex = [
  6956. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6957. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6958. ];
  6959. width = texture._width;
  6960. height = texture._height;
  6961. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6962. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6963. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6964. if (!noMipmap && isPot) {
  6965. if (mipmmapGenerator) {
  6966. var arrayTemp = [];
  6967. // Data are known to be in +X +Y +Z -X -Y -Z
  6968. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6969. arrayTemp.push(rgbeDataArrays[0]); // +X
  6970. arrayTemp.push(rgbeDataArrays[3]); // -X
  6971. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6972. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6973. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6974. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6975. var mipData = mipmmapGenerator(arrayTemp);
  6976. for (var level = 0; level < mipData.length; level++) {
  6977. var mipSize = width >> level;
  6978. // mipData is order in +X -X +Y -Y +Z -Z
  6979. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6980. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6981. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6982. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6983. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6984. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6985. }
  6986. }
  6987. else {
  6988. // Data are known to be in +X +Y +Z -X -Y -Z
  6989. for (var index = 0; index < facesIndex.length; index++) {
  6990. var faceData = rgbeDataArrays[index];
  6991. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6992. }
  6993. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6994. }
  6995. }
  6996. else {
  6997. noMipmap = true;
  6998. }
  6999. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7002. }
  7003. else {
  7004. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7005. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7006. }
  7007. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7008. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7009. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7010. texture.isReady = true;
  7011. _this.resetTextureCache();
  7012. scene._removePendingData(texture);
  7013. };
  7014. BABYLON.Tools.LoadFile(url, function (data) {
  7015. internalCallback(data);
  7016. }, onerror, scene.database, true);
  7017. return texture;
  7018. };
  7019. ;
  7020. Engine.prototype._releaseTexture = function (texture) {
  7021. var gl = this._gl;
  7022. if (texture._framebuffer) {
  7023. gl.deleteFramebuffer(texture._framebuffer);
  7024. }
  7025. if (texture._depthBuffer) {
  7026. gl.deleteRenderbuffer(texture._depthBuffer);
  7027. }
  7028. gl.deleteTexture(texture);
  7029. // Unbind channels
  7030. this.unbindAllTextures();
  7031. var index = this._loadedTexturesCache.indexOf(texture);
  7032. if (index !== -1) {
  7033. this._loadedTexturesCache.splice(index, 1);
  7034. }
  7035. };
  7036. Engine.prototype.bindSamplers = function (effect) {
  7037. this._gl.useProgram(effect.getProgram());
  7038. var samplers = effect.getSamplers();
  7039. for (var index = 0; index < samplers.length; index++) {
  7040. var uniform = effect.getUniform(samplers[index]);
  7041. this._gl.uniform1i(uniform, index);
  7042. }
  7043. this._currentEffect = null;
  7044. };
  7045. Engine.prototype._bindTexture = function (channel, texture) {
  7046. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7047. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7048. this._activeTexturesCache[channel] = null;
  7049. };
  7050. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7051. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7052. };
  7053. Engine.prototype.unbindAllTextures = function () {
  7054. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7055. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7056. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7057. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7058. this._activeTexturesCache[channel] = null;
  7059. }
  7060. };
  7061. Engine.prototype.setTexture = function (channel, texture) {
  7062. if (channel < 0) {
  7063. return;
  7064. }
  7065. // Not ready?
  7066. if (!texture || !texture.isReady()) {
  7067. if (this._activeTexturesCache[channel] != null) {
  7068. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7069. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7070. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7071. this._activeTexturesCache[channel] = null;
  7072. }
  7073. return;
  7074. }
  7075. // Video
  7076. var alreadyActivated = false;
  7077. if (texture instanceof BABYLON.VideoTexture) {
  7078. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7079. alreadyActivated = true;
  7080. texture.update();
  7081. }
  7082. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7083. texture.delayLoad();
  7084. return;
  7085. }
  7086. if (this._activeTexturesCache[channel] === texture) {
  7087. return;
  7088. }
  7089. this._activeTexturesCache[channel] = texture;
  7090. var internalTexture = texture.getInternalTexture();
  7091. if (!alreadyActivated) {
  7092. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7093. }
  7094. if (internalTexture.isCube) {
  7095. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7096. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7097. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7098. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7099. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7100. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7101. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7102. }
  7103. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7104. }
  7105. else {
  7106. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7107. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7108. internalTexture._cachedWrapU = texture.wrapU;
  7109. switch (texture.wrapU) {
  7110. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7111. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7112. break;
  7113. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7114. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7115. break;
  7116. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7117. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7118. break;
  7119. }
  7120. }
  7121. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7122. internalTexture._cachedWrapV = texture.wrapV;
  7123. switch (texture.wrapV) {
  7124. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7125. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7126. break;
  7127. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7128. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7129. break;
  7130. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7131. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7132. break;
  7133. }
  7134. }
  7135. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7136. }
  7137. };
  7138. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7139. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7140. var value = texture.anisotropicFilteringLevel;
  7141. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7142. value = 1;
  7143. }
  7144. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7145. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7146. texture._cachedAnisotropicFilteringLevel = value;
  7147. }
  7148. };
  7149. Engine.prototype.readPixels = function (x, y, width, height) {
  7150. var data = new Uint8Array(height * width * 4);
  7151. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7152. return data;
  7153. };
  7154. Engine.prototype.releaseInternalTexture = function (texture) {
  7155. if (!texture) {
  7156. return;
  7157. }
  7158. texture.references--;
  7159. // Final reference ?
  7160. if (texture.references === 0) {
  7161. var texturesCache = this.getLoadedTexturesCache();
  7162. var index = texturesCache.indexOf(texture);
  7163. if (index > -1) {
  7164. texturesCache.splice(index, 1);
  7165. }
  7166. this._releaseTexture(texture);
  7167. }
  7168. };
  7169. // Dispose
  7170. Engine.prototype.dispose = function () {
  7171. this.hideLoadingUI();
  7172. this.stopRenderLoop();
  7173. // Release scenes
  7174. while (this.scenes.length) {
  7175. this.scenes[0].dispose();
  7176. }
  7177. // Release audio engine
  7178. Engine.audioEngine.dispose();
  7179. // Release effects
  7180. for (var name in this._compiledEffects) {
  7181. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7182. }
  7183. // Unbind
  7184. for (var i in this._vertexAttribArrays) {
  7185. //making sure this is a string
  7186. var iAsNumber = +i;
  7187. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7188. continue;
  7189. }
  7190. this._gl.disableVertexAttribArray(iAsNumber);
  7191. }
  7192. this._gl = null;
  7193. // Events
  7194. window.removeEventListener("blur", this._onBlur);
  7195. window.removeEventListener("focus", this._onFocus);
  7196. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7197. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7198. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7199. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7200. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7201. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7202. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7203. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7204. };
  7205. // Loading screen
  7206. Engine.prototype.displayLoadingUI = function () {
  7207. this._loadingScreen.displayLoadingUI();
  7208. };
  7209. Engine.prototype.hideLoadingUI = function () {
  7210. this._loadingScreen.hideLoadingUI();
  7211. };
  7212. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7213. get: function () {
  7214. return this._loadingScreen;
  7215. },
  7216. set: function (loadingScreen) {
  7217. this._loadingScreen = loadingScreen;
  7218. },
  7219. enumerable: true,
  7220. configurable: true
  7221. });
  7222. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7223. set: function (text) {
  7224. this._loadingScreen.loadingUIText = text;
  7225. },
  7226. enumerable: true,
  7227. configurable: true
  7228. });
  7229. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7230. set: function (color) {
  7231. this._loadingScreen.loadingUIBackgroundColor = color;
  7232. },
  7233. enumerable: true,
  7234. configurable: true
  7235. });
  7236. // FPS
  7237. Engine.prototype.getFps = function () {
  7238. return this.fps;
  7239. };
  7240. Engine.prototype.getDeltaTime = function () {
  7241. return this.deltaTime;
  7242. };
  7243. Engine.prototype._measureFps = function () {
  7244. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7245. var length = this.previousFramesDuration.length;
  7246. if (length >= 2) {
  7247. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7248. }
  7249. if (length >= this.fpsRange) {
  7250. if (length > this.fpsRange) {
  7251. this.previousFramesDuration.splice(0, 1);
  7252. length = this.previousFramesDuration.length;
  7253. }
  7254. var sum = 0;
  7255. for (var id = 0; id < length - 1; id++) {
  7256. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7257. }
  7258. this.fps = 1000.0 / (sum / (length - 1));
  7259. }
  7260. };
  7261. // Statics
  7262. Engine.isSupported = function () {
  7263. try {
  7264. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7265. if (navigator.isCocoonJS) {
  7266. return true;
  7267. }
  7268. var tempcanvas = document.createElement("canvas");
  7269. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7270. return gl != null && !!window.WebGLRenderingContext;
  7271. }
  7272. catch (e) {
  7273. return false;
  7274. }
  7275. };
  7276. // Const statics
  7277. Engine._ALPHA_DISABLE = 0;
  7278. Engine._ALPHA_ADD = 1;
  7279. Engine._ALPHA_COMBINE = 2;
  7280. Engine._ALPHA_SUBTRACT = 3;
  7281. Engine._ALPHA_MULTIPLY = 4;
  7282. Engine._ALPHA_MAXIMIZED = 5;
  7283. Engine._ALPHA_ONEONE = 6;
  7284. Engine._DELAYLOADSTATE_NONE = 0;
  7285. Engine._DELAYLOADSTATE_LOADED = 1;
  7286. Engine._DELAYLOADSTATE_LOADING = 2;
  7287. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7288. Engine._TEXTUREFORMAT_ALPHA = 0;
  7289. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7290. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7291. Engine._TEXTUREFORMAT_RGB = 4;
  7292. Engine._TEXTUREFORMAT_RGBA = 5;
  7293. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7294. Engine._TEXTURETYPE_FLOAT = 1;
  7295. // Updatable statics so stick with vars here
  7296. Engine.CollisionsEpsilon = 0.001;
  7297. Engine.CodeRepository = "src/";
  7298. Engine.ShadersRepository = "src/Shaders/";
  7299. return Engine;
  7300. })();
  7301. BABYLON.Engine = Engine;
  7302. })(BABYLON || (BABYLON = {}));
  7303. var BABYLON;
  7304. (function (BABYLON) {
  7305. /**
  7306. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7307. */
  7308. var Node = (function () {
  7309. /**
  7310. * @constructor
  7311. * @param {string} name - the name and id to be given to this node
  7312. * @param {BABYLON.Scene} the scene this node will be added to
  7313. */
  7314. function Node(name, scene) {
  7315. this.state = "";
  7316. this.animations = new Array();
  7317. this._ranges = {};
  7318. this._childrenFlag = -1;
  7319. this._isEnabled = true;
  7320. this._isReady = true;
  7321. this._currentRenderId = -1;
  7322. this._parentRenderId = -1;
  7323. this.name = name;
  7324. this.id = name;
  7325. this._scene = scene;
  7326. this._initCache();
  7327. }
  7328. Object.defineProperty(Node.prototype, "parent", {
  7329. get: function () {
  7330. return this._parentNode;
  7331. },
  7332. set: function (parent) {
  7333. if (this._parentNode === parent) {
  7334. return;
  7335. }
  7336. if (this._parentNode) {
  7337. var index = this._parentNode._children.indexOf(this);
  7338. if (index !== -1) {
  7339. this._parentNode._children.splice(index, 1);
  7340. }
  7341. }
  7342. this._parentNode = parent;
  7343. if (this._parentNode) {
  7344. if (!this._parentNode._children) {
  7345. this._parentNode._children = new Array();
  7346. }
  7347. this._parentNode._children.push(this);
  7348. }
  7349. },
  7350. enumerable: true,
  7351. configurable: true
  7352. });
  7353. Node.prototype.getScene = function () {
  7354. return this._scene;
  7355. };
  7356. Node.prototype.getEngine = function () {
  7357. return this._scene.getEngine();
  7358. };
  7359. // override it in derived class
  7360. Node.prototype.getWorldMatrix = function () {
  7361. return BABYLON.Matrix.Identity();
  7362. };
  7363. // override it in derived class if you add new variables to the cache
  7364. // and call the parent class method
  7365. Node.prototype._initCache = function () {
  7366. this._cache = {};
  7367. this._cache.parent = undefined;
  7368. };
  7369. Node.prototype.updateCache = function (force) {
  7370. if (!force && this.isSynchronized())
  7371. return;
  7372. this._cache.parent = this.parent;
  7373. this._updateCache();
  7374. };
  7375. // override it in derived class if you add new variables to the cache
  7376. // and call the parent class method if !ignoreParentClass
  7377. Node.prototype._updateCache = function (ignoreParentClass) {
  7378. };
  7379. // override it in derived class if you add new variables to the cache
  7380. Node.prototype._isSynchronized = function () {
  7381. return true;
  7382. };
  7383. Node.prototype._markSyncedWithParent = function () {
  7384. this._parentRenderId = this.parent._currentRenderId;
  7385. };
  7386. Node.prototype.isSynchronizedWithParent = function () {
  7387. if (!this.parent) {
  7388. return true;
  7389. }
  7390. if (this._parentRenderId !== this.parent._currentRenderId) {
  7391. return false;
  7392. }
  7393. return this.parent.isSynchronized();
  7394. };
  7395. Node.prototype.isSynchronized = function (updateCache) {
  7396. var check = this.hasNewParent();
  7397. check = check || !this.isSynchronizedWithParent();
  7398. check = check || !this._isSynchronized();
  7399. if (updateCache)
  7400. this.updateCache(true);
  7401. return !check;
  7402. };
  7403. Node.prototype.hasNewParent = function (update) {
  7404. if (this._cache.parent === this.parent)
  7405. return false;
  7406. if (update)
  7407. this._cache.parent = this.parent;
  7408. return true;
  7409. };
  7410. /**
  7411. * Is this node ready to be used/rendered
  7412. * @return {boolean} is it ready
  7413. */
  7414. Node.prototype.isReady = function () {
  7415. return this._isReady;
  7416. };
  7417. /**
  7418. * Is this node enabled.
  7419. * If the node has a parent and is enabled, the parent will be inspected as well.
  7420. * @return {boolean} whether this node (and its parent) is enabled.
  7421. * @see setEnabled
  7422. */
  7423. Node.prototype.isEnabled = function () {
  7424. if (!this._isEnabled) {
  7425. return false;
  7426. }
  7427. if (this.parent) {
  7428. return this.parent.isEnabled();
  7429. }
  7430. return true;
  7431. };
  7432. /**
  7433. * Set the enabled state of this node.
  7434. * @param {boolean} value - the new enabled state
  7435. * @see isEnabled
  7436. */
  7437. Node.prototype.setEnabled = function (value) {
  7438. this._isEnabled = value;
  7439. };
  7440. /**
  7441. * Is this node a descendant of the given node.
  7442. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7443. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7444. * @see parent
  7445. */
  7446. Node.prototype.isDescendantOf = function (ancestor) {
  7447. if (this.parent) {
  7448. if (this.parent === ancestor) {
  7449. return true;
  7450. }
  7451. return this.parent.isDescendantOf(ancestor);
  7452. }
  7453. return false;
  7454. };
  7455. /**
  7456. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7457. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7458. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7459. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7460. */
  7461. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7462. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7463. if (!this._children) {
  7464. return;
  7465. }
  7466. for (var index = 0; index < this._children.length; index++) {
  7467. var item = this._children[index];
  7468. if (!predicate || predicate(item)) {
  7469. results.push(item);
  7470. }
  7471. if (!directDescendantsOnly) {
  7472. item._getDescendants(results, false, predicate);
  7473. }
  7474. }
  7475. };
  7476. /**
  7477. * Will return all nodes that have this node as ascendant.
  7478. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7479. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7480. * @return {BABYLON.Node[]} all children nodes of all types.
  7481. */
  7482. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7483. var results = [];
  7484. this._getDescendants(results, directDescendantsOnly, predicate);
  7485. return results;
  7486. };
  7487. /**
  7488. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7489. * @Deprecated, legacy support.
  7490. * use getDecendants instead.
  7491. */
  7492. Node.prototype.getChildren = function (predicate) {
  7493. return this.getDescendants(true, predicate);
  7494. };
  7495. /**
  7496. * Get all child-meshes of this node.
  7497. */
  7498. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7499. var results = [];
  7500. this._getDescendants(results, directDecendantsOnly, function (node) {
  7501. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7502. });
  7503. return results;
  7504. };
  7505. Node.prototype._setReady = function (state) {
  7506. if (state === this._isReady) {
  7507. return;
  7508. }
  7509. if (!state) {
  7510. this._isReady = false;
  7511. return;
  7512. }
  7513. this._isReady = true;
  7514. if (this.onReady) {
  7515. this.onReady(this);
  7516. }
  7517. };
  7518. Node.prototype.getAnimationByName = function (name) {
  7519. for (var i = 0; i < this.animations.length; i++) {
  7520. var animation = this.animations[i];
  7521. if (animation.name === name) {
  7522. return animation;
  7523. }
  7524. }
  7525. return null;
  7526. };
  7527. Node.prototype.createAnimationRange = function (name, from, to) {
  7528. // check name not already in use
  7529. if (!this._ranges[name]) {
  7530. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7531. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7532. if (this.animations[i]) {
  7533. this.animations[i].createRange(name, from, to);
  7534. }
  7535. }
  7536. }
  7537. };
  7538. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7539. if (deleteFrames === void 0) { deleteFrames = true; }
  7540. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7541. if (this.animations[i]) {
  7542. this.animations[i].deleteRange(name, deleteFrames);
  7543. }
  7544. }
  7545. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7546. };
  7547. Node.prototype.getAnimationRange = function (name) {
  7548. return this._ranges[name];
  7549. };
  7550. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7551. var range = this.getAnimationRange(name);
  7552. if (!range) {
  7553. return null;
  7554. }
  7555. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7556. };
  7557. Node.prototype.serializeAnimationRanges = function () {
  7558. var serializationRanges = [];
  7559. for (var name in this._ranges) {
  7560. var range = {};
  7561. range.name = name;
  7562. range.from = this._ranges[name].from;
  7563. range.to = this._ranges[name].to;
  7564. serializationRanges.push(range);
  7565. }
  7566. return serializationRanges;
  7567. };
  7568. Node.prototype.dispose = function () {
  7569. this.parent = null;
  7570. };
  7571. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7572. if (parsedNode.ranges) {
  7573. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7574. var data = parsedNode.ranges[index];
  7575. node.createAnimationRange(data.name, data.from, data.to);
  7576. }
  7577. }
  7578. };
  7579. __decorate([
  7580. BABYLON.serialize()
  7581. ], Node.prototype, "name", void 0);
  7582. __decorate([
  7583. BABYLON.serialize()
  7584. ], Node.prototype, "id", void 0);
  7585. __decorate([
  7586. BABYLON.serialize()
  7587. ], Node.prototype, "uniqueId", void 0);
  7588. __decorate([
  7589. BABYLON.serialize()
  7590. ], Node.prototype, "state", void 0);
  7591. return Node;
  7592. })();
  7593. BABYLON.Node = Node;
  7594. })(BABYLON || (BABYLON = {}));
  7595. var BABYLON;
  7596. (function (BABYLON) {
  7597. var FilesInput = (function () {
  7598. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7599. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7600. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7601. this._engine = p_engine;
  7602. this._canvas = p_canvas;
  7603. this._currentScene = p_scene;
  7604. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7605. this._progressCallback = p_progressCallback;
  7606. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7607. this._textureLoadingCallback = p_textureLoadingCallback;
  7608. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7609. }
  7610. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7611. var _this = this;
  7612. if (p_elementToMonitor) {
  7613. this._elementToMonitor = p_elementToMonitor;
  7614. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7615. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7616. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7617. }
  7618. };
  7619. FilesInput.prototype.renderFunction = function () {
  7620. if (this._additionnalRenderLoopLogicCallback) {
  7621. this._additionnalRenderLoopLogicCallback();
  7622. }
  7623. if (this._currentScene) {
  7624. if (this._textureLoadingCallback) {
  7625. var remaining = this._currentScene.getWaitingItemsCount();
  7626. if (remaining > 0) {
  7627. this._textureLoadingCallback(remaining);
  7628. }
  7629. }
  7630. this._currentScene.render();
  7631. }
  7632. };
  7633. FilesInput.prototype.drag = function (e) {
  7634. e.stopPropagation();
  7635. e.preventDefault();
  7636. };
  7637. FilesInput.prototype.drop = function (eventDrop) {
  7638. eventDrop.stopPropagation();
  7639. eventDrop.preventDefault();
  7640. this.loadFiles(eventDrop);
  7641. };
  7642. FilesInput.prototype.loadFiles = function (event) {
  7643. if (this._startingProcessingFilesCallback)
  7644. this._startingProcessingFilesCallback();
  7645. // Handling data transfer via drag'n'drop
  7646. if (event && event.dataTransfer && event.dataTransfer.files) {
  7647. this._filesToLoad = event.dataTransfer.files;
  7648. }
  7649. // Handling files from input files
  7650. if (event && event.target && event.target.files) {
  7651. this._filesToLoad = event.target.files;
  7652. }
  7653. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7654. for (var i = 0; i < this._filesToLoad.length; i++) {
  7655. switch (this._filesToLoad[i].type) {
  7656. case "image/jpeg":
  7657. case "image/png":
  7658. case "image/bmp":
  7659. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7660. break;
  7661. case "image/targa":
  7662. case "image/vnd.ms-dds":
  7663. case "audio/wav":
  7664. case "audio/x-wav":
  7665. case "audio/mp3":
  7666. case "audio/mpeg":
  7667. case "audio/mpeg3":
  7668. case "audio/x-mpeg-3":
  7669. case "audio/ogg":
  7670. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7671. break;
  7672. default:
  7673. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7674. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7675. }
  7676. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7677. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7678. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7679. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7680. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7681. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7682. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7683. this._sceneFileToLoad = this._filesToLoad[i];
  7684. }
  7685. break;
  7686. }
  7687. }
  7688. this.reload();
  7689. }
  7690. };
  7691. FilesInput.prototype.reload = function () {
  7692. var _this = this;
  7693. var that = this;
  7694. // If a ".babylon" file has been provided
  7695. if (this._sceneFileToLoad) {
  7696. if (this._currentScene) {
  7697. if (BABYLON.Tools.errorsCount > 0) {
  7698. BABYLON.Tools.ClearLogCache();
  7699. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7700. }
  7701. this._engine.stopRenderLoop();
  7702. this._currentScene.dispose();
  7703. }
  7704. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7705. that._currentScene = newScene;
  7706. // Wait for textures and shaders to be ready
  7707. that._currentScene.executeWhenReady(function () {
  7708. // Attach camera to canvas inputs
  7709. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7710. that._currentScene.createDefaultCameraOrLight();
  7711. }
  7712. that._currentScene.activeCamera.attachControl(that._canvas);
  7713. if (that._sceneLoadedCallback) {
  7714. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7715. }
  7716. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7717. });
  7718. }, function (progress) {
  7719. if (_this._progressCallback) {
  7720. _this._progressCallback(progress);
  7721. }
  7722. });
  7723. }
  7724. else {
  7725. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7726. }
  7727. };
  7728. FilesInput.FilesTextures = new Array();
  7729. FilesInput.FilesToLoad = new Array();
  7730. return FilesInput;
  7731. })();
  7732. BABYLON.FilesInput = FilesInput;
  7733. })(BABYLON || (BABYLON = {}));
  7734. var BABYLON;
  7735. (function (BABYLON) {
  7736. var IntersectionInfo = (function () {
  7737. function IntersectionInfo(bu, bv, distance) {
  7738. this.bu = bu;
  7739. this.bv = bv;
  7740. this.distance = distance;
  7741. this.faceId = 0;
  7742. this.subMeshId = 0;
  7743. }
  7744. return IntersectionInfo;
  7745. })();
  7746. BABYLON.IntersectionInfo = IntersectionInfo;
  7747. var PickingInfo = (function () {
  7748. function PickingInfo() {
  7749. this.hit = false;
  7750. this.distance = 0;
  7751. this.pickedPoint = null;
  7752. this.pickedMesh = null;
  7753. this.bu = 0;
  7754. this.bv = 0;
  7755. this.faceId = -1;
  7756. this.subMeshId = 0;
  7757. this.pickedSprite = null;
  7758. }
  7759. // Methods
  7760. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7761. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7762. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7763. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7764. return null;
  7765. }
  7766. var indices = this.pickedMesh.getIndices();
  7767. var result;
  7768. if (useVerticesNormals) {
  7769. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7770. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7771. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7772. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7773. normal0 = normal0.scale(this.bu);
  7774. normal1 = normal1.scale(this.bv);
  7775. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7776. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7777. }
  7778. else {
  7779. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7780. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7781. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7782. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7783. var p1p2 = vertex1.subtract(vertex2);
  7784. var p3p2 = vertex3.subtract(vertex2);
  7785. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7786. }
  7787. if (useWorldCoordinates) {
  7788. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7789. }
  7790. return BABYLON.Vector3.Normalize(result);
  7791. };
  7792. PickingInfo.prototype.getTextureCoordinates = function () {
  7793. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7794. return null;
  7795. }
  7796. var indices = this.pickedMesh.getIndices();
  7797. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7798. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7799. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7800. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7801. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7802. uv1 = uv1.scale(this.bu);
  7803. uv2 = uv2.scale(this.bv);
  7804. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7805. };
  7806. return PickingInfo;
  7807. })();
  7808. BABYLON.PickingInfo = PickingInfo;
  7809. })(BABYLON || (BABYLON = {}));
  7810. var BABYLON;
  7811. (function (BABYLON) {
  7812. var BoundingSphere = (function () {
  7813. function BoundingSphere(minimum, maximum) {
  7814. this.minimum = minimum;
  7815. this.maximum = maximum;
  7816. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7817. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7818. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7819. this.radius = distance * 0.5;
  7820. this.centerWorld = BABYLON.Vector3.Zero();
  7821. this._update(BABYLON.Matrix.Identity());
  7822. }
  7823. // Methods
  7824. BoundingSphere.prototype._update = function (world) {
  7825. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7826. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7827. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7828. };
  7829. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7830. for (var i = 0; i < 6; i++) {
  7831. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7832. return false;
  7833. }
  7834. return true;
  7835. };
  7836. BoundingSphere.prototype.intersectsPoint = function (point) {
  7837. var x = this.centerWorld.x - point.x;
  7838. var y = this.centerWorld.y - point.y;
  7839. var z = this.centerWorld.z - point.z;
  7840. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7841. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7842. return false;
  7843. return true;
  7844. };
  7845. // Statics
  7846. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7847. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7848. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7849. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7850. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7851. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7852. return false;
  7853. return true;
  7854. };
  7855. return BoundingSphere;
  7856. })();
  7857. BABYLON.BoundingSphere = BoundingSphere;
  7858. })(BABYLON || (BABYLON = {}));
  7859. var BABYLON;
  7860. (function (BABYLON) {
  7861. var BoundingBox = (function () {
  7862. function BoundingBox(minimum, maximum) {
  7863. this.minimum = minimum;
  7864. this.maximum = maximum;
  7865. this.vectors = new Array();
  7866. this.vectorsWorld = new Array();
  7867. // Bounding vectors
  7868. this.vectors.push(this.minimum.clone());
  7869. this.vectors.push(this.maximum.clone());
  7870. this.vectors.push(this.minimum.clone());
  7871. this.vectors[2].x = this.maximum.x;
  7872. this.vectors.push(this.minimum.clone());
  7873. this.vectors[3].y = this.maximum.y;
  7874. this.vectors.push(this.minimum.clone());
  7875. this.vectors[4].z = this.maximum.z;
  7876. this.vectors.push(this.maximum.clone());
  7877. this.vectors[5].z = this.minimum.z;
  7878. this.vectors.push(this.maximum.clone());
  7879. this.vectors[6].x = this.minimum.x;
  7880. this.vectors.push(this.maximum.clone());
  7881. this.vectors[7].y = this.minimum.y;
  7882. // OBB
  7883. this.center = this.maximum.add(this.minimum).scale(0.5);
  7884. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7885. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7886. // World
  7887. for (var index = 0; index < this.vectors.length; index++) {
  7888. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7889. }
  7890. this.minimumWorld = BABYLON.Vector3.Zero();
  7891. this.maximumWorld = BABYLON.Vector3.Zero();
  7892. this._update(BABYLON.Matrix.Identity());
  7893. }
  7894. // Methods
  7895. BoundingBox.prototype.getWorldMatrix = function () {
  7896. return this._worldMatrix;
  7897. };
  7898. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7899. this._worldMatrix.copyFrom(matrix);
  7900. return this;
  7901. };
  7902. BoundingBox.prototype._update = function (world) {
  7903. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7904. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7905. for (var index = 0; index < this.vectors.length; index++) {
  7906. var v = this.vectorsWorld[index];
  7907. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7908. if (v.x < this.minimumWorld.x)
  7909. this.minimumWorld.x = v.x;
  7910. if (v.y < this.minimumWorld.y)
  7911. this.minimumWorld.y = v.y;
  7912. if (v.z < this.minimumWorld.z)
  7913. this.minimumWorld.z = v.z;
  7914. if (v.x > this.maximumWorld.x)
  7915. this.maximumWorld.x = v.x;
  7916. if (v.y > this.maximumWorld.y)
  7917. this.maximumWorld.y = v.y;
  7918. if (v.z > this.maximumWorld.z)
  7919. this.maximumWorld.z = v.z;
  7920. }
  7921. // OBB
  7922. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7923. this.center.scaleInPlace(0.5);
  7924. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7925. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7926. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7927. this._worldMatrix = world;
  7928. };
  7929. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7930. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7931. };
  7932. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7933. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7934. };
  7935. BoundingBox.prototype.intersectsPoint = function (point) {
  7936. var delta = -BABYLON.Epsilon;
  7937. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7938. return false;
  7939. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7940. return false;
  7941. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7942. return false;
  7943. return true;
  7944. };
  7945. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7946. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7947. };
  7948. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7949. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7950. return false;
  7951. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7952. return false;
  7953. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7954. return false;
  7955. return true;
  7956. };
  7957. // Statics
  7958. BoundingBox.Intersects = function (box0, box1) {
  7959. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7960. return false;
  7961. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7962. return false;
  7963. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7964. return false;
  7965. return true;
  7966. };
  7967. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7968. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7969. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7970. return (num <= (sphereRadius * sphereRadius));
  7971. };
  7972. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7973. for (var p = 0; p < 6; p++) {
  7974. for (var i = 0; i < 8; i++) {
  7975. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7976. return false;
  7977. }
  7978. }
  7979. }
  7980. return true;
  7981. };
  7982. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7983. for (var p = 0; p < 6; p++) {
  7984. var inCount = 8;
  7985. for (var i = 0; i < 8; i++) {
  7986. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7987. --inCount;
  7988. }
  7989. else {
  7990. break;
  7991. }
  7992. }
  7993. if (inCount === 0)
  7994. return false;
  7995. }
  7996. return true;
  7997. };
  7998. return BoundingBox;
  7999. })();
  8000. BABYLON.BoundingBox = BoundingBox;
  8001. })(BABYLON || (BABYLON = {}));
  8002. var BABYLON;
  8003. (function (BABYLON) {
  8004. var computeBoxExtents = function (axis, box) {
  8005. var p = BABYLON.Vector3.Dot(box.center, axis);
  8006. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8007. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8008. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8009. var r = r0 + r1 + r2;
  8010. return {
  8011. min: p - r,
  8012. max: p + r
  8013. };
  8014. };
  8015. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8016. var axisOverlap = function (axis, box0, box1) {
  8017. var result0 = computeBoxExtents(axis, box0);
  8018. var result1 = computeBoxExtents(axis, box1);
  8019. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8020. };
  8021. var BoundingInfo = (function () {
  8022. function BoundingInfo(minimum, maximum) {
  8023. this.minimum = minimum;
  8024. this.maximum = maximum;
  8025. this._isLocked = false;
  8026. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8027. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8028. }
  8029. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8030. get: function () {
  8031. return this._isLocked;
  8032. },
  8033. set: function (value) {
  8034. this._isLocked = value;
  8035. },
  8036. enumerable: true,
  8037. configurable: true
  8038. });
  8039. // Methods
  8040. BoundingInfo.prototype.update = function (world) {
  8041. if (this._isLocked) {
  8042. return;
  8043. }
  8044. this.boundingBox._update(world);
  8045. this.boundingSphere._update(world);
  8046. };
  8047. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8048. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8049. return false;
  8050. return this.boundingBox.isInFrustum(frustumPlanes);
  8051. };
  8052. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8053. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8054. };
  8055. BoundingInfo.prototype._checkCollision = function (collider) {
  8056. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8057. };
  8058. BoundingInfo.prototype.intersectsPoint = function (point) {
  8059. if (!this.boundingSphere.centerWorld) {
  8060. return false;
  8061. }
  8062. if (!this.boundingSphere.intersectsPoint(point)) {
  8063. return false;
  8064. }
  8065. if (!this.boundingBox.intersectsPoint(point)) {
  8066. return false;
  8067. }
  8068. return true;
  8069. };
  8070. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8071. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8072. return false;
  8073. }
  8074. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8075. return false;
  8076. }
  8077. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8078. return false;
  8079. }
  8080. if (!precise) {
  8081. return true;
  8082. }
  8083. var box0 = this.boundingBox;
  8084. var box1 = boundingInfo.boundingBox;
  8085. if (!axisOverlap(box0.directions[0], box0, box1))
  8086. return false;
  8087. if (!axisOverlap(box0.directions[1], box0, box1))
  8088. return false;
  8089. if (!axisOverlap(box0.directions[2], box0, box1))
  8090. return false;
  8091. if (!axisOverlap(box1.directions[0], box0, box1))
  8092. return false;
  8093. if (!axisOverlap(box1.directions[1], box0, box1))
  8094. return false;
  8095. if (!axisOverlap(box1.directions[2], box0, box1))
  8096. return false;
  8097. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8098. return false;
  8099. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8100. return false;
  8101. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8102. return false;
  8103. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8104. return false;
  8105. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8106. return false;
  8107. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8108. return false;
  8109. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8110. return false;
  8111. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8112. return false;
  8113. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8114. return false;
  8115. return true;
  8116. };
  8117. return BoundingInfo;
  8118. })();
  8119. BABYLON.BoundingInfo = BoundingInfo;
  8120. })(BABYLON || (BABYLON = {}));
  8121. var BABYLON;
  8122. (function (BABYLON) {
  8123. var Ray = (function () {
  8124. function Ray(origin, direction, length) {
  8125. if (length === void 0) { length = Number.MAX_VALUE; }
  8126. this.origin = origin;
  8127. this.direction = direction;
  8128. this.length = length;
  8129. }
  8130. // Methods
  8131. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8132. var d = 0.0;
  8133. var maxValue = Number.MAX_VALUE;
  8134. var inv;
  8135. var min;
  8136. var max;
  8137. var temp;
  8138. if (Math.abs(this.direction.x) < 0.0000001) {
  8139. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8140. return false;
  8141. }
  8142. }
  8143. else {
  8144. inv = 1.0 / this.direction.x;
  8145. min = (minimum.x - this.origin.x) * inv;
  8146. max = (maximum.x - this.origin.x) * inv;
  8147. if (max === -Infinity) {
  8148. max = Infinity;
  8149. }
  8150. if (min > max) {
  8151. temp = min;
  8152. min = max;
  8153. max = temp;
  8154. }
  8155. d = Math.max(min, d);
  8156. maxValue = Math.min(max, maxValue);
  8157. if (d > maxValue) {
  8158. return false;
  8159. }
  8160. }
  8161. if (Math.abs(this.direction.y) < 0.0000001) {
  8162. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8163. return false;
  8164. }
  8165. }
  8166. else {
  8167. inv = 1.0 / this.direction.y;
  8168. min = (minimum.y - this.origin.y) * inv;
  8169. max = (maximum.y - this.origin.y) * inv;
  8170. if (max === -Infinity) {
  8171. max = Infinity;
  8172. }
  8173. if (min > max) {
  8174. temp = min;
  8175. min = max;
  8176. max = temp;
  8177. }
  8178. d = Math.max(min, d);
  8179. maxValue = Math.min(max, maxValue);
  8180. if (d > maxValue) {
  8181. return false;
  8182. }
  8183. }
  8184. if (Math.abs(this.direction.z) < 0.0000001) {
  8185. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8186. return false;
  8187. }
  8188. }
  8189. else {
  8190. inv = 1.0 / this.direction.z;
  8191. min = (minimum.z - this.origin.z) * inv;
  8192. max = (maximum.z - this.origin.z) * inv;
  8193. if (max === -Infinity) {
  8194. max = Infinity;
  8195. }
  8196. if (min > max) {
  8197. temp = min;
  8198. min = max;
  8199. max = temp;
  8200. }
  8201. d = Math.max(min, d);
  8202. maxValue = Math.min(max, maxValue);
  8203. if (d > maxValue) {
  8204. return false;
  8205. }
  8206. }
  8207. return true;
  8208. };
  8209. Ray.prototype.intersectsBox = function (box) {
  8210. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8211. };
  8212. Ray.prototype.intersectsSphere = function (sphere) {
  8213. var x = sphere.center.x - this.origin.x;
  8214. var y = sphere.center.y - this.origin.y;
  8215. var z = sphere.center.z - this.origin.z;
  8216. var pyth = (x * x) + (y * y) + (z * z);
  8217. var rr = sphere.radius * sphere.radius;
  8218. if (pyth <= rr) {
  8219. return true;
  8220. }
  8221. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8222. if (dot < 0.0) {
  8223. return false;
  8224. }
  8225. var temp = pyth - (dot * dot);
  8226. return temp <= rr;
  8227. };
  8228. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8229. if (!this._edge1) {
  8230. this._edge1 = BABYLON.Vector3.Zero();
  8231. this._edge2 = BABYLON.Vector3.Zero();
  8232. this._pvec = BABYLON.Vector3.Zero();
  8233. this._tvec = BABYLON.Vector3.Zero();
  8234. this._qvec = BABYLON.Vector3.Zero();
  8235. }
  8236. vertex1.subtractToRef(vertex0, this._edge1);
  8237. vertex2.subtractToRef(vertex0, this._edge2);
  8238. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8239. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8240. if (det === 0) {
  8241. return null;
  8242. }
  8243. var invdet = 1 / det;
  8244. this.origin.subtractToRef(vertex0, this._tvec);
  8245. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8246. if (bu < 0 || bu > 1.0) {
  8247. return null;
  8248. }
  8249. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8250. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8251. if (bv < 0 || bu + bv > 1.0) {
  8252. return null;
  8253. }
  8254. //check if the distance is longer than the predefined length.
  8255. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8256. if (distance > this.length) {
  8257. return null;
  8258. }
  8259. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8260. };
  8261. Ray.prototype.intersectsPlane = function (plane) {
  8262. var distance;
  8263. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8264. if (Math.abs(result1) < 9.99999997475243E-07) {
  8265. return null;
  8266. }
  8267. else {
  8268. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8269. distance = (-plane.d - result2) / result1;
  8270. if (distance < 0.0) {
  8271. if (distance < -9.99999997475243E-07) {
  8272. return null;
  8273. }
  8274. else {
  8275. return 0;
  8276. }
  8277. }
  8278. return distance;
  8279. }
  8280. };
  8281. /**
  8282. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8283. * @param sega the first point of the segment to test the intersection against
  8284. * @param segb the second point of the segment to test the intersection against
  8285. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8286. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8287. */
  8288. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8289. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8290. var u = segb.subtract(sega);
  8291. var v = rsegb.subtract(this.origin);
  8292. var w = sega.subtract(this.origin);
  8293. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8294. var b = BABYLON.Vector3.Dot(u, v);
  8295. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8296. var d = BABYLON.Vector3.Dot(u, w);
  8297. var e = BABYLON.Vector3.Dot(v, w);
  8298. var D = a * c - b * b; // always >= 0
  8299. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8300. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8301. // compute the line parameters of the two closest points
  8302. if (D < Ray.smallnum) {
  8303. sN = 0.0; // force using point P0 on segment S1
  8304. sD = 1.0; // to prevent possible division by 0.0 later
  8305. tN = e;
  8306. tD = c;
  8307. }
  8308. else {
  8309. sN = (b * e - c * d);
  8310. tN = (a * e - b * d);
  8311. if (sN < 0.0) {
  8312. sN = 0.0;
  8313. tN = e;
  8314. tD = c;
  8315. }
  8316. else if (sN > sD) {
  8317. sN = sD;
  8318. tN = e + b;
  8319. tD = c;
  8320. }
  8321. }
  8322. if (tN < 0.0) {
  8323. tN = 0.0;
  8324. // recompute sc for this edge
  8325. if (-d < 0.0) {
  8326. sN = 0.0;
  8327. }
  8328. else if (-d > a)
  8329. sN = sD;
  8330. else {
  8331. sN = -d;
  8332. sD = a;
  8333. }
  8334. }
  8335. else if (tN > tD) {
  8336. tN = tD;
  8337. // recompute sc for this edge
  8338. if ((-d + b) < 0.0) {
  8339. sN = 0;
  8340. }
  8341. else if ((-d + b) > a) {
  8342. sN = sD;
  8343. }
  8344. else {
  8345. sN = (-d + b);
  8346. sD = a;
  8347. }
  8348. }
  8349. // finally do the division to get sc and tc
  8350. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8351. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8352. // get the difference of the two closest points
  8353. var qtc = v.multiplyByFloats(tc, tc, tc);
  8354. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  8355. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8356. if (isIntersected) {
  8357. return qtc.length();
  8358. }
  8359. return -1;
  8360. };
  8361. // Statics
  8362. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8363. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8364. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8365. var direction = end.subtract(start);
  8366. direction.normalize();
  8367. return new Ray(start, direction);
  8368. };
  8369. /**
  8370. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  8371. * transformed to the given world matrix.
  8372. * @param origin The origin point
  8373. * @param end The end point
  8374. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8375. */
  8376. Ray.CreateNewFromTo = function (origin, end, world) {
  8377. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8378. var direction = end.subtract(origin);
  8379. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8380. direction.normalize();
  8381. return Ray.Transform(new Ray(origin, direction, length), world);
  8382. };
  8383. Ray.Transform = function (ray, matrix) {
  8384. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8385. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8386. newDirection.normalize();
  8387. return new Ray(newOrigin, newDirection, ray.length);
  8388. };
  8389. Ray.smallnum = 0.00000001;
  8390. Ray.rayl = 10e8;
  8391. return Ray;
  8392. })();
  8393. BABYLON.Ray = Ray;
  8394. })(BABYLON || (BABYLON = {}));
  8395. var BABYLON;
  8396. (function (BABYLON) {
  8397. var AbstractMesh = (function (_super) {
  8398. __extends(AbstractMesh, _super);
  8399. // Constructor
  8400. function AbstractMesh(name, scene) {
  8401. var _this = this;
  8402. _super.call(this, name, scene);
  8403. // Events
  8404. /**
  8405. * An event triggered when this mesh collides with another one
  8406. * @type {BABYLON.Observable}
  8407. */
  8408. this.onCollideObservable = new BABYLON.Observable();
  8409. /**
  8410. * An event triggered when the collision's position changes
  8411. * @type {BABYLON.Observable}
  8412. */
  8413. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8414. /**
  8415. * An event triggered after the world matrix is updated
  8416. * @type {BABYLON.Observable}
  8417. */
  8418. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8419. // Properties
  8420. this.definedFacingForward = true; // orientation for POV movement & rotation
  8421. this.position = new BABYLON.Vector3(0, 0, 0);
  8422. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8423. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8424. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8425. this.visibility = 1.0;
  8426. this.alphaIndex = Number.MAX_VALUE;
  8427. this.infiniteDistance = false;
  8428. this.isVisible = true;
  8429. this.isPickable = true;
  8430. this.showBoundingBox = false;
  8431. this.showSubMeshesBoundingBox = false;
  8432. this.onDispose = null;
  8433. this.isBlocker = false;
  8434. this.renderingGroupId = 0;
  8435. this.receiveShadows = false;
  8436. this.renderOutline = false;
  8437. this.outlineColor = BABYLON.Color3.Red();
  8438. this.outlineWidth = 0.02;
  8439. this.renderOverlay = false;
  8440. this.overlayColor = BABYLON.Color3.Red();
  8441. this.overlayAlpha = 0.5;
  8442. this.hasVertexAlpha = false;
  8443. this.useVertexColors = true;
  8444. this.applyFog = true;
  8445. this.computeBonesUsingShaders = true;
  8446. this.scalingDeterminant = 1;
  8447. this.numBoneInfluencers = 4;
  8448. this.useOctreeForRenderingSelection = true;
  8449. this.useOctreeForPicking = true;
  8450. this.useOctreeForCollisions = true;
  8451. this.layerMask = 0x0FFFFFFF;
  8452. this.alwaysSelectAsActiveMesh = false;
  8453. // Collisions
  8454. this._checkCollisions = false;
  8455. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8456. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8457. this._collider = new BABYLON.Collider();
  8458. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8459. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8460. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8461. // Edges
  8462. this.edgesWidth = 1;
  8463. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8464. // Cache
  8465. this._localWorld = BABYLON.Matrix.Zero();
  8466. this._worldMatrix = BABYLON.Matrix.Zero();
  8467. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8468. this._absolutePosition = BABYLON.Vector3.Zero();
  8469. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8470. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8471. this._isDirty = false;
  8472. this._pivotMatrix = BABYLON.Matrix.Identity();
  8473. this._isDisposed = false;
  8474. this._renderId = 0;
  8475. this._intersectionsInProgress = new Array();
  8476. this._isWorldMatrixFrozen = false;
  8477. this._unIndexed = false;
  8478. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8479. if (collidedMesh === void 0) { collidedMesh = null; }
  8480. //TODO move this to the collision coordinator!
  8481. if (_this.getScene().workerCollisions)
  8482. newPosition.multiplyInPlace(_this._collider.radius);
  8483. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8484. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8485. _this.position.addInPlace(_this._diffPositionForCollisions);
  8486. }
  8487. if (collidedMesh) {
  8488. _this.onCollideObservable.notifyObservers(collidedMesh);
  8489. }
  8490. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8491. };
  8492. scene.addMesh(this);
  8493. }
  8494. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8495. get: function () {
  8496. return AbstractMesh._BILLBOARDMODE_NONE;
  8497. },
  8498. enumerable: true,
  8499. configurable: true
  8500. });
  8501. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8502. get: function () {
  8503. return AbstractMesh._BILLBOARDMODE_X;
  8504. },
  8505. enumerable: true,
  8506. configurable: true
  8507. });
  8508. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8509. get: function () {
  8510. return AbstractMesh._BILLBOARDMODE_Y;
  8511. },
  8512. enumerable: true,
  8513. configurable: true
  8514. });
  8515. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8516. get: function () {
  8517. return AbstractMesh._BILLBOARDMODE_Z;
  8518. },
  8519. enumerable: true,
  8520. configurable: true
  8521. });
  8522. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8523. get: function () {
  8524. return AbstractMesh._BILLBOARDMODE_ALL;
  8525. },
  8526. enumerable: true,
  8527. configurable: true
  8528. });
  8529. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8530. set: function (callback) {
  8531. if (this._onCollideObserver) {
  8532. this.onCollideObservable.remove(this._onCollideObserver);
  8533. }
  8534. this._onCollideObserver = this.onCollideObservable.add(callback);
  8535. },
  8536. enumerable: true,
  8537. configurable: true
  8538. });
  8539. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8540. set: function (callback) {
  8541. if (this._onCollisionPositionChangeObserver) {
  8542. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8543. }
  8544. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8545. },
  8546. enumerable: true,
  8547. configurable: true
  8548. });
  8549. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8550. get: function () {
  8551. return this._skeleton;
  8552. },
  8553. set: function (value) {
  8554. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8555. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8556. }
  8557. if (value && value.needInitialSkinMatrix) {
  8558. value._registerMeshWithPoseMatrix(this);
  8559. }
  8560. this._skeleton = value;
  8561. if (!this._skeleton) {
  8562. this._bonesTransformMatrices = null;
  8563. }
  8564. },
  8565. enumerable: true,
  8566. configurable: true
  8567. });
  8568. /**
  8569. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8570. */
  8571. AbstractMesh.prototype.toString = function (fullDetails) {
  8572. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8573. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8574. if (this._skeleton) {
  8575. ret += ", skeleton: " + this._skeleton.name;
  8576. }
  8577. if (fullDetails) {
  8578. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8579. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8580. }
  8581. return ret;
  8582. };
  8583. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8584. /**
  8585. * Getting the rotation object.
  8586. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8587. */
  8588. get: function () {
  8589. return this._rotation;
  8590. },
  8591. set: function (newRotation) {
  8592. this._rotation = newRotation;
  8593. },
  8594. enumerable: true,
  8595. configurable: true
  8596. });
  8597. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8598. get: function () {
  8599. return this._scaling;
  8600. },
  8601. set: function (newScaling) {
  8602. this._scaling = newScaling;
  8603. if (this.physicsImpostor) {
  8604. this.physicsImpostor.forceUpdate();
  8605. }
  8606. },
  8607. enumerable: true,
  8608. configurable: true
  8609. });
  8610. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8611. get: function () {
  8612. return this._rotationQuaternion;
  8613. },
  8614. set: function (quaternion) {
  8615. this._rotationQuaternion = quaternion;
  8616. //reset the rotation vector.
  8617. if (quaternion && this.rotation.length()) {
  8618. this.rotation.copyFromFloats(0, 0, 0);
  8619. }
  8620. },
  8621. enumerable: true,
  8622. configurable: true
  8623. });
  8624. // Methods
  8625. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8626. this._poseMatrix.copyFrom(matrix);
  8627. };
  8628. AbstractMesh.prototype.getPoseMatrix = function () {
  8629. return this._poseMatrix;
  8630. };
  8631. AbstractMesh.prototype.disableEdgesRendering = function () {
  8632. if (this._edgesRenderer !== undefined) {
  8633. this._edgesRenderer.dispose();
  8634. this._edgesRenderer = undefined;
  8635. }
  8636. };
  8637. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8638. if (epsilon === void 0) { epsilon = 0.95; }
  8639. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8640. this.disableEdgesRendering();
  8641. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8642. };
  8643. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8644. get: function () {
  8645. return false;
  8646. },
  8647. enumerable: true,
  8648. configurable: true
  8649. });
  8650. AbstractMesh.prototype.getLOD = function (camera) {
  8651. return this;
  8652. };
  8653. AbstractMesh.prototype.getTotalVertices = function () {
  8654. return 0;
  8655. };
  8656. AbstractMesh.prototype.getIndices = function () {
  8657. return null;
  8658. };
  8659. AbstractMesh.prototype.getVerticesData = function (kind) {
  8660. return null;
  8661. };
  8662. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8663. return false;
  8664. };
  8665. AbstractMesh.prototype.getBoundingInfo = function () {
  8666. if (this._masterMesh) {
  8667. return this._masterMesh.getBoundingInfo();
  8668. }
  8669. if (!this._boundingInfo) {
  8670. this._updateBoundingInfo();
  8671. }
  8672. return this._boundingInfo;
  8673. };
  8674. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8675. get: function () {
  8676. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8677. },
  8678. enumerable: true,
  8679. configurable: true
  8680. });
  8681. AbstractMesh.prototype._preActivate = function () {
  8682. };
  8683. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8684. };
  8685. AbstractMesh.prototype._activate = function (renderId) {
  8686. this._renderId = renderId;
  8687. };
  8688. AbstractMesh.prototype.getWorldMatrix = function () {
  8689. if (this._masterMesh) {
  8690. return this._masterMesh.getWorldMatrix();
  8691. }
  8692. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8693. this.computeWorldMatrix();
  8694. }
  8695. return this._worldMatrix;
  8696. };
  8697. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8698. get: function () {
  8699. return this._worldMatrix;
  8700. },
  8701. enumerable: true,
  8702. configurable: true
  8703. });
  8704. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8705. get: function () {
  8706. return this._absolutePosition;
  8707. },
  8708. enumerable: true,
  8709. configurable: true
  8710. });
  8711. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8712. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8713. this.computeWorldMatrix(true);
  8714. this._isWorldMatrixFrozen = true;
  8715. };
  8716. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8717. this._isWorldMatrixFrozen = false;
  8718. this.computeWorldMatrix(true);
  8719. };
  8720. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8721. get: function () {
  8722. return this._isWorldMatrixFrozen;
  8723. },
  8724. enumerable: true,
  8725. configurable: true
  8726. });
  8727. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8728. axis.normalize();
  8729. if (!this.rotationQuaternion) {
  8730. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8731. this.rotation = BABYLON.Vector3.Zero();
  8732. }
  8733. var rotationQuaternion;
  8734. if (!space || space === BABYLON.Space.LOCAL) {
  8735. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8736. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8737. }
  8738. else {
  8739. if (this.parent) {
  8740. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8741. invertParentWorldMatrix.invert();
  8742. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8743. }
  8744. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8745. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8746. }
  8747. };
  8748. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8749. var displacementVector = axis.scale(distance);
  8750. if (!space || space === BABYLON.Space.LOCAL) {
  8751. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8752. this.setPositionWithLocalVector(tempV3);
  8753. }
  8754. else {
  8755. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8756. }
  8757. };
  8758. AbstractMesh.prototype.getAbsolutePosition = function () {
  8759. this.computeWorldMatrix();
  8760. return this._absolutePosition;
  8761. };
  8762. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8763. if (!absolutePosition) {
  8764. return;
  8765. }
  8766. var absolutePositionX;
  8767. var absolutePositionY;
  8768. var absolutePositionZ;
  8769. if (absolutePosition.x === undefined) {
  8770. if (arguments.length < 3) {
  8771. return;
  8772. }
  8773. absolutePositionX = arguments[0];
  8774. absolutePositionY = arguments[1];
  8775. absolutePositionZ = arguments[2];
  8776. }
  8777. else {
  8778. absolutePositionX = absolutePosition.x;
  8779. absolutePositionY = absolutePosition.y;
  8780. absolutePositionZ = absolutePosition.z;
  8781. }
  8782. if (this.parent) {
  8783. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8784. invertParentWorldMatrix.invert();
  8785. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8786. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8787. }
  8788. else {
  8789. this.position.x = absolutePositionX;
  8790. this.position.y = absolutePositionY;
  8791. this.position.z = absolutePositionZ;
  8792. }
  8793. };
  8794. // ================================== Point of View Movement =================================
  8795. /**
  8796. * Perform relative position change from the point of view of behind the front of the mesh.
  8797. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8798. * Supports definition of mesh facing forward or backward.
  8799. * @param {number} amountRight
  8800. * @param {number} amountUp
  8801. * @param {number} amountForward
  8802. */
  8803. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8804. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8805. };
  8806. /**
  8807. * Calculate relative position change from the point of view of behind the front of the mesh.
  8808. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8809. * Supports definition of mesh facing forward or backward.
  8810. * @param {number} amountRight
  8811. * @param {number} amountUp
  8812. * @param {number} amountForward
  8813. */
  8814. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8815. var rotMatrix = new BABYLON.Matrix();
  8816. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8817. rotQuaternion.toRotationMatrix(rotMatrix);
  8818. var translationDelta = BABYLON.Vector3.Zero();
  8819. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8820. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8821. return translationDelta;
  8822. };
  8823. // ================================== Point of View Rotation =================================
  8824. /**
  8825. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8826. * Supports definition of mesh facing forward or backward.
  8827. * @param {number} flipBack
  8828. * @param {number} twirlClockwise
  8829. * @param {number} tiltRight
  8830. */
  8831. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8832. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8833. };
  8834. /**
  8835. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8836. * Supports definition of mesh facing forward or backward.
  8837. * @param {number} flipBack
  8838. * @param {number} twirlClockwise
  8839. * @param {number} tiltRight
  8840. */
  8841. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8842. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8843. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8844. };
  8845. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8846. this._pivotMatrix = matrix;
  8847. this._cache.pivotMatrixUpdated = true;
  8848. };
  8849. AbstractMesh.prototype.getPivotMatrix = function () {
  8850. return this._pivotMatrix;
  8851. };
  8852. AbstractMesh.prototype._isSynchronized = function () {
  8853. if (this._isDirty) {
  8854. return false;
  8855. }
  8856. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8857. return false;
  8858. if (this._cache.pivotMatrixUpdated) {
  8859. return false;
  8860. }
  8861. if (this.infiniteDistance) {
  8862. return false;
  8863. }
  8864. if (!this._cache.position.equals(this.position))
  8865. return false;
  8866. if (this.rotationQuaternion) {
  8867. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8868. return false;
  8869. }
  8870. else {
  8871. if (!this._cache.rotation.equals(this.rotation))
  8872. return false;
  8873. }
  8874. if (!this._cache.scaling.equals(this.scaling))
  8875. return false;
  8876. return true;
  8877. };
  8878. AbstractMesh.prototype._initCache = function () {
  8879. _super.prototype._initCache.call(this);
  8880. this._cache.localMatrixUpdated = false;
  8881. this._cache.position = BABYLON.Vector3.Zero();
  8882. this._cache.scaling = BABYLON.Vector3.Zero();
  8883. this._cache.rotation = BABYLON.Vector3.Zero();
  8884. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8885. this._cache.billboardMode = -1;
  8886. };
  8887. AbstractMesh.prototype.markAsDirty = function (property) {
  8888. if (property === "rotation") {
  8889. this.rotationQuaternion = null;
  8890. }
  8891. this._currentRenderId = Number.MAX_VALUE;
  8892. this._isDirty = true;
  8893. };
  8894. AbstractMesh.prototype._updateBoundingInfo = function () {
  8895. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8896. this._boundingInfo.update(this.worldMatrixFromCache);
  8897. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8898. };
  8899. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8900. if (!this.subMeshes) {
  8901. return;
  8902. }
  8903. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8904. var subMesh = this.subMeshes[subIndex];
  8905. if (!subMesh.IsGlobal) {
  8906. subMesh.updateBoundingInfo(matrix);
  8907. }
  8908. }
  8909. };
  8910. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8911. if (this._isWorldMatrixFrozen) {
  8912. return this._worldMatrix;
  8913. }
  8914. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8915. this._currentRenderId = this.getScene().getRenderId();
  8916. return this._worldMatrix;
  8917. }
  8918. this._cache.position.copyFrom(this.position);
  8919. this._cache.scaling.copyFrom(this.scaling);
  8920. this._cache.pivotMatrixUpdated = false;
  8921. this._cache.billboardMode = this.billboardMode;
  8922. this._currentRenderId = this.getScene().getRenderId();
  8923. this._isDirty = false;
  8924. // Scaling
  8925. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8926. // Rotation
  8927. //rotate, if quaternion is set and rotation was used
  8928. if (this.rotationQuaternion) {
  8929. var len = this.rotation.length();
  8930. if (len) {
  8931. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8932. this.rotation.copyFromFloats(0, 0, 0);
  8933. }
  8934. }
  8935. if (this.rotationQuaternion) {
  8936. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8937. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8938. }
  8939. else {
  8940. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8941. this._cache.rotation.copyFrom(this.rotation);
  8942. }
  8943. // Translation
  8944. if (this.infiniteDistance && !this.parent) {
  8945. var camera = this.getScene().activeCamera;
  8946. if (camera) {
  8947. var cameraWorldMatrix = camera.getWorldMatrix();
  8948. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8949. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8950. }
  8951. }
  8952. else {
  8953. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8954. }
  8955. // Composing transformations
  8956. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8957. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8958. // Billboarding
  8959. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8960. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  8961. var localPosition = BABYLON.Tmp.Vector3[0];
  8962. if (this.parent && this.parent.getWorldMatrix) {
  8963. this._markSyncedWithParent();
  8964. var parentMatrix;
  8965. if (this._meshToBoneReferal) {
  8966. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8967. parentMatrix = BABYLON.Tmp.Matrix[6];
  8968. }
  8969. else {
  8970. parentMatrix = this.parent.getWorldMatrix();
  8971. }
  8972. BABYLON.Vector3.TransformCoordinatesToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  8973. localPosition = BABYLON.Tmp.Vector3[1];
  8974. }
  8975. var zero = this.getScene().activeCamera.globalPosition.clone();
  8976. if (this.parent && this.parent.position) {
  8977. localPosition.addInPlace(this.parent.position);
  8978. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8979. }
  8980. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8981. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8982. zero.x = localPosition.x + BABYLON.Epsilon;
  8983. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8984. zero.y = localPosition.y + BABYLON.Epsilon;
  8985. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8986. zero.z = localPosition.z + BABYLON.Epsilon;
  8987. }
  8988. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8989. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8990. BABYLON.Tmp.Matrix[3].invert();
  8991. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8992. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8993. }
  8994. // Local world
  8995. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8996. // Parent
  8997. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8998. this._markSyncedWithParent();
  8999. if (this._meshToBoneReferal) {
  9000. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9001. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9002. }
  9003. else {
  9004. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9005. }
  9006. }
  9007. else {
  9008. this._worldMatrix.copyFrom(this._localWorld);
  9009. }
  9010. // Bounding info
  9011. this._updateBoundingInfo();
  9012. // Absolute position
  9013. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9014. // Callbacks
  9015. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9016. if (!this._poseMatrix) {
  9017. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9018. }
  9019. return this._worldMatrix;
  9020. };
  9021. /**
  9022. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9023. * @param func: callback function to add
  9024. */
  9025. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9026. this.onAfterWorldMatrixUpdateObservable.add(func);
  9027. };
  9028. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9029. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9030. };
  9031. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9032. this.computeWorldMatrix();
  9033. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9034. };
  9035. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9036. this.computeWorldMatrix();
  9037. var invLocalWorldMatrix = this._localWorld.clone();
  9038. invLocalWorldMatrix.invert();
  9039. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9040. };
  9041. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9042. this.computeWorldMatrix(true);
  9043. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9044. };
  9045. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9046. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9047. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9048. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9049. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9050. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9051. /// <returns>Mesh oriented towards targetMesh</returns>
  9052. yawCor = yawCor || 0; // default to zero if undefined
  9053. pitchCor = pitchCor || 0;
  9054. rollCor = rollCor || 0;
  9055. var dv = targetPoint.subtract(this.position);
  9056. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9057. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9058. var pitch = Math.atan2(dv.y, len);
  9059. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9060. };
  9061. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9062. this._meshToBoneReferal = affectedMesh;
  9063. this.parent = bone;
  9064. if (bone.getWorldMatrix().determinant() < 0) {
  9065. this.scalingDeterminant *= -1;
  9066. }
  9067. };
  9068. AbstractMesh.prototype.detachFromBone = function () {
  9069. if (this.parent.getWorldMatrix().determinant() < 0) {
  9070. this.scalingDeterminant *= -1;
  9071. }
  9072. this._meshToBoneReferal = null;
  9073. this.parent = null;
  9074. };
  9075. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9076. return this._boundingInfo.isInFrustum(frustumPlanes);
  9077. };
  9078. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9079. if (!camera) {
  9080. camera = this.getScene().activeCamera;
  9081. }
  9082. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9083. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9084. return false;
  9085. }
  9086. return true;
  9087. };
  9088. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9089. if (!this._boundingInfo || !mesh._boundingInfo) {
  9090. return false;
  9091. }
  9092. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9093. };
  9094. AbstractMesh.prototype.intersectsPoint = function (point) {
  9095. if (!this._boundingInfo) {
  9096. return false;
  9097. }
  9098. return this._boundingInfo.intersectsPoint(point);
  9099. };
  9100. // Physics
  9101. /**
  9102. * @Deprecated. Use new PhysicsImpostor instead.
  9103. * */
  9104. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9105. //legacy support
  9106. if (impostor.impostor) {
  9107. options = impostor;
  9108. impostor = impostor.impostor;
  9109. }
  9110. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9111. return this.physicsImpostor.physicsBody;
  9112. };
  9113. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9114. return this.physicsImpostor;
  9115. };
  9116. /**
  9117. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9118. */
  9119. AbstractMesh.prototype.getPhysicsMass = function () {
  9120. return this.physicsImpostor.getParam("mass");
  9121. };
  9122. /**
  9123. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9124. */
  9125. AbstractMesh.prototype.getPhysicsFriction = function () {
  9126. return this.physicsImpostor.getParam("friction");
  9127. };
  9128. /**
  9129. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9130. */
  9131. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9132. return this.physicsImpostor.getParam("resitution");
  9133. };
  9134. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9135. if (!camera) {
  9136. camera = this.getScene().activeCamera;
  9137. }
  9138. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9139. };
  9140. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9141. if (!camera) {
  9142. camera = this.getScene().activeCamera;
  9143. }
  9144. return this.absolutePosition.subtract(camera.position).length();
  9145. };
  9146. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9147. if (!this.physicsImpostor) {
  9148. return;
  9149. }
  9150. this.physicsImpostor.applyImpulse(force, contactPoint);
  9151. };
  9152. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9153. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9154. return;
  9155. }
  9156. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9157. mainPivot: pivot1,
  9158. connectedPivot: pivot2,
  9159. nativeParams: options
  9160. });
  9161. };
  9162. /**
  9163. * @Deprecated
  9164. */
  9165. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9166. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9167. this.updatePhysicsBody();
  9168. };
  9169. /**
  9170. * @Deprecated
  9171. * Calling this function is not needed anymore.
  9172. * The physics engine takes care of transofmration automatically.
  9173. */
  9174. AbstractMesh.prototype.updatePhysicsBody = function () {
  9175. //Unneeded
  9176. };
  9177. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9178. // Collisions
  9179. get: function () {
  9180. return this._checkCollisions;
  9181. },
  9182. set: function (collisionEnabled) {
  9183. this._checkCollisions = collisionEnabled;
  9184. if (this.getScene().workerCollisions) {
  9185. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9186. }
  9187. },
  9188. enumerable: true,
  9189. configurable: true
  9190. });
  9191. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9192. var globalPosition = this.getAbsolutePosition();
  9193. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9194. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9195. this._collider.radius = this.ellipsoid;
  9196. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9197. };
  9198. // Submeshes octree
  9199. /**
  9200. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9201. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9202. */
  9203. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9204. if (maxCapacity === void 0) { maxCapacity = 64; }
  9205. if (maxDepth === void 0) { maxDepth = 2; }
  9206. if (!this._submeshesOctree) {
  9207. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9208. }
  9209. this.computeWorldMatrix(true);
  9210. // Update octree
  9211. var bbox = this.getBoundingInfo().boundingBox;
  9212. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9213. return this._submeshesOctree;
  9214. };
  9215. // Collisions
  9216. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9217. this._generatePointsArray();
  9218. // Transformation
  9219. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9220. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9221. subMesh._lastColliderWorldVertices = [];
  9222. subMesh._trianglePlanes = [];
  9223. var start = subMesh.verticesStart;
  9224. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9225. for (var i = start; i < end; i++) {
  9226. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9227. }
  9228. }
  9229. // Collide
  9230. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9231. if (collider.collisionFound) {
  9232. collider.collidedMesh = this;
  9233. }
  9234. };
  9235. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9236. var subMeshes;
  9237. var len;
  9238. // Octrees
  9239. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9240. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9241. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9242. len = intersections.length;
  9243. subMeshes = intersections.data;
  9244. }
  9245. else {
  9246. subMeshes = this.subMeshes;
  9247. len = subMeshes.length;
  9248. }
  9249. for (var index = 0; index < len; index++) {
  9250. var subMesh = subMeshes[index];
  9251. // Bounding test
  9252. if (len > 1 && !subMesh._checkCollision(collider))
  9253. continue;
  9254. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9255. }
  9256. };
  9257. AbstractMesh.prototype._checkCollision = function (collider) {
  9258. // Bounding box test
  9259. if (!this._boundingInfo._checkCollision(collider))
  9260. return;
  9261. // Transformation matrix
  9262. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9263. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9264. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9265. };
  9266. // Picking
  9267. AbstractMesh.prototype._generatePointsArray = function () {
  9268. return false;
  9269. };
  9270. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9271. var pickingInfo = new BABYLON.PickingInfo();
  9272. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9273. return pickingInfo;
  9274. }
  9275. if (!this._generatePointsArray()) {
  9276. return pickingInfo;
  9277. }
  9278. var intersectInfo = null;
  9279. // Octrees
  9280. var subMeshes;
  9281. var len;
  9282. if (this._submeshesOctree && this.useOctreeForPicking) {
  9283. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9284. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9285. len = intersections.length;
  9286. subMeshes = intersections.data;
  9287. }
  9288. else {
  9289. subMeshes = this.subMeshes;
  9290. len = subMeshes.length;
  9291. }
  9292. for (var index = 0; index < len; index++) {
  9293. var subMesh = subMeshes[index];
  9294. // Bounding test
  9295. if (len > 1 && !subMesh.canIntersects(ray))
  9296. continue;
  9297. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9298. if (currentIntersectInfo) {
  9299. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9300. intersectInfo = currentIntersectInfo;
  9301. intersectInfo.subMeshId = index;
  9302. if (fastCheck) {
  9303. break;
  9304. }
  9305. }
  9306. }
  9307. }
  9308. if (intersectInfo) {
  9309. // Get picked point
  9310. var world = this.getWorldMatrix();
  9311. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9312. var direction = ray.direction.clone();
  9313. direction = direction.scale(intersectInfo.distance);
  9314. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9315. var pickedPoint = worldOrigin.add(worldDirection);
  9316. // Return result
  9317. pickingInfo.hit = true;
  9318. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9319. pickingInfo.pickedPoint = pickedPoint;
  9320. pickingInfo.pickedMesh = this;
  9321. pickingInfo.bu = intersectInfo.bu;
  9322. pickingInfo.bv = intersectInfo.bv;
  9323. pickingInfo.faceId = intersectInfo.faceId;
  9324. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9325. return pickingInfo;
  9326. }
  9327. return pickingInfo;
  9328. };
  9329. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9330. return null;
  9331. };
  9332. AbstractMesh.prototype.releaseSubMeshes = function () {
  9333. if (this.subMeshes) {
  9334. while (this.subMeshes.length) {
  9335. this.subMeshes[0].dispose();
  9336. }
  9337. }
  9338. else {
  9339. this.subMeshes = new Array();
  9340. }
  9341. };
  9342. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9343. var _this = this;
  9344. var index;
  9345. // Action manager
  9346. if (this.actionManager) {
  9347. this.actionManager.dispose();
  9348. this.actionManager = null;
  9349. }
  9350. // Skeleton
  9351. this.skeleton = null;
  9352. // Animations
  9353. this.getScene().stopAnimation(this);
  9354. // Physics
  9355. if (this.physicsImpostor) {
  9356. this.physicsImpostor.dispose();
  9357. }
  9358. // Intersections in progress
  9359. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9360. var other = this._intersectionsInProgress[index];
  9361. var pos = other._intersectionsInProgress.indexOf(this);
  9362. other._intersectionsInProgress.splice(pos, 1);
  9363. }
  9364. this._intersectionsInProgress = [];
  9365. // Lights
  9366. var lights = this.getScene().lights;
  9367. lights.forEach(function (light) {
  9368. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9369. if (meshIndex !== -1) {
  9370. light.includedOnlyMeshes.splice(meshIndex, 1);
  9371. }
  9372. meshIndex = light.excludedMeshes.indexOf(_this);
  9373. if (meshIndex !== -1) {
  9374. light.excludedMeshes.splice(meshIndex, 1);
  9375. }
  9376. });
  9377. // Edges
  9378. if (this._edgesRenderer) {
  9379. this._edgesRenderer.dispose();
  9380. this._edgesRenderer = null;
  9381. }
  9382. // SubMeshes
  9383. this.releaseSubMeshes();
  9384. // Remove from scene
  9385. this.getScene().removeMesh(this);
  9386. if (!doNotRecurse) {
  9387. // Particles
  9388. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9389. if (this.getScene().particleSystems[index].emitter === this) {
  9390. this.getScene().particleSystems[index].dispose();
  9391. index--;
  9392. }
  9393. }
  9394. // Children
  9395. var objects = this.getDescendants(true);
  9396. for (index = 0; index < objects.length; index++) {
  9397. objects[index].dispose();
  9398. }
  9399. }
  9400. else {
  9401. var childMeshes = this.getChildMeshes(true);
  9402. for (index = 0; index < childMeshes.length; index++) {
  9403. var child = childMeshes[index];
  9404. child.parent = null;
  9405. child.computeWorldMatrix(true);
  9406. }
  9407. }
  9408. _super.prototype.dispose.call(this);
  9409. this.onAfterWorldMatrixUpdateObservable.clear();
  9410. this._isDisposed = true;
  9411. // Callback
  9412. if (this.onDispose) {
  9413. this.onDispose();
  9414. }
  9415. };
  9416. // Statics
  9417. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9418. AbstractMesh._BILLBOARDMODE_X = 1;
  9419. AbstractMesh._BILLBOARDMODE_Y = 2;
  9420. AbstractMesh._BILLBOARDMODE_Z = 4;
  9421. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9422. return AbstractMesh;
  9423. })(BABYLON.Node);
  9424. BABYLON.AbstractMesh = AbstractMesh;
  9425. })(BABYLON || (BABYLON = {}));
  9426. var BABYLON;
  9427. (function (BABYLON) {
  9428. var Light = (function (_super) {
  9429. __extends(Light, _super);
  9430. function Light(name, scene) {
  9431. _super.call(this, name, scene);
  9432. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9433. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9434. this.intensity = 1.0;
  9435. this.range = Number.MAX_VALUE;
  9436. this.includeOnlyWithLayerMask = 0;
  9437. this.includedOnlyMeshes = new Array();
  9438. this.excludedMeshes = new Array();
  9439. this.excludeWithLayerMask = 0;
  9440. // PBR Properties.
  9441. this.radius = 0.00001;
  9442. this._excludedMeshesIds = new Array();
  9443. this._includedOnlyMeshesIds = new Array();
  9444. scene.addLight(this);
  9445. }
  9446. /**
  9447. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9448. */
  9449. Light.prototype.toString = function (fullDetails) {
  9450. var ret = "Name: " + this.name;
  9451. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9452. if (this.animations) {
  9453. for (var i = 0; i < this.animations.length; i++) {
  9454. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9455. }
  9456. }
  9457. if (fullDetails) {
  9458. }
  9459. return ret;
  9460. };
  9461. Light.prototype.getShadowGenerator = function () {
  9462. return this._shadowGenerator;
  9463. };
  9464. Light.prototype.getAbsolutePosition = function () {
  9465. return BABYLON.Vector3.Zero();
  9466. };
  9467. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9468. };
  9469. Light.prototype._getWorldMatrix = function () {
  9470. return BABYLON.Matrix.Identity();
  9471. };
  9472. Light.prototype.canAffectMesh = function (mesh) {
  9473. if (!mesh) {
  9474. return true;
  9475. }
  9476. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9477. return false;
  9478. }
  9479. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9480. return false;
  9481. }
  9482. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9483. return false;
  9484. }
  9485. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9486. return false;
  9487. }
  9488. return true;
  9489. };
  9490. Light.prototype.getWorldMatrix = function () {
  9491. this._currentRenderId = this.getScene().getRenderId();
  9492. var worldMatrix = this._getWorldMatrix();
  9493. if (this.parent && this.parent.getWorldMatrix) {
  9494. if (!this._parentedWorldMatrix) {
  9495. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9496. }
  9497. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9498. this._markSyncedWithParent();
  9499. return this._parentedWorldMatrix;
  9500. }
  9501. return worldMatrix;
  9502. };
  9503. Light.prototype.dispose = function () {
  9504. if (this._shadowGenerator) {
  9505. this._shadowGenerator.dispose();
  9506. this._shadowGenerator = null;
  9507. }
  9508. // Animations
  9509. this.getScene().stopAnimation(this);
  9510. // Remove from scene
  9511. this.getScene().removeLight(this);
  9512. _super.prototype.dispose.call(this);
  9513. };
  9514. Light.prototype.getTypeID = function () {
  9515. return 0;
  9516. };
  9517. Light.prototype.clone = function (name) {
  9518. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9519. };
  9520. Light.prototype.serialize = function () {
  9521. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9522. // Type
  9523. serializationObject.type = this.getTypeID();
  9524. // Parent
  9525. if (this.parent) {
  9526. serializationObject.parentId = this.parent.id;
  9527. }
  9528. // Inclusion / exclusions
  9529. if (this.excludedMeshes.length > 0) {
  9530. serializationObject.excludedMeshesIds = [];
  9531. this.excludedMeshes.forEach(function (mesh) {
  9532. serializationObject.excludedMeshesIds.push(mesh.id);
  9533. });
  9534. }
  9535. if (this.includedOnlyMeshes.length > 0) {
  9536. serializationObject.includedOnlyMeshesIds = [];
  9537. this.includedOnlyMeshes.forEach(function (mesh) {
  9538. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9539. });
  9540. }
  9541. // Animations
  9542. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9543. serializationObject.ranges = this.serializeAnimationRanges();
  9544. return serializationObject;
  9545. };
  9546. Light.GetConstructorFromName = function (type, name, scene) {
  9547. switch (type) {
  9548. case 0:
  9549. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9550. case 1:
  9551. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9552. case 2:
  9553. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9554. case 3:
  9555. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9556. }
  9557. };
  9558. Light.Parse = function (parsedLight, scene) {
  9559. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9560. // Inclusion / exclusions
  9561. if (parsedLight.excludedMeshesIds) {
  9562. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9563. }
  9564. if (parsedLight.includedOnlyMeshesIds) {
  9565. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9566. }
  9567. // Parent
  9568. if (parsedLight.parentId) {
  9569. light._waitingParentId = parsedLight.parentId;
  9570. }
  9571. // Animations
  9572. if (parsedLight.animations) {
  9573. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9574. var parsedAnimation = parsedLight.animations[animationIndex];
  9575. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9576. }
  9577. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9578. }
  9579. if (parsedLight.autoAnimate) {
  9580. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9581. }
  9582. return light;
  9583. };
  9584. __decorate([
  9585. BABYLON.serializeAsColor3()
  9586. ], Light.prototype, "diffuse", void 0);
  9587. __decorate([
  9588. BABYLON.serializeAsColor3()
  9589. ], Light.prototype, "specular", void 0);
  9590. __decorate([
  9591. BABYLON.serialize()
  9592. ], Light.prototype, "intensity", void 0);
  9593. __decorate([
  9594. BABYLON.serialize()
  9595. ], Light.prototype, "range", void 0);
  9596. __decorate([
  9597. BABYLON.serialize()
  9598. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9599. __decorate([
  9600. BABYLON.serialize()
  9601. ], Light.prototype, "excludeWithLayerMask", void 0);
  9602. __decorate([
  9603. BABYLON.serialize()
  9604. ], Light.prototype, "radius", void 0);
  9605. return Light;
  9606. })(BABYLON.Node);
  9607. BABYLON.Light = Light;
  9608. })(BABYLON || (BABYLON = {}));
  9609. var BABYLON;
  9610. (function (BABYLON) {
  9611. var PointLight = (function (_super) {
  9612. __extends(PointLight, _super);
  9613. function PointLight(name, position, scene) {
  9614. _super.call(this, name, scene);
  9615. this.position = position;
  9616. }
  9617. PointLight.prototype.getAbsolutePosition = function () {
  9618. return this.transformedPosition ? this.transformedPosition : this.position;
  9619. };
  9620. PointLight.prototype.computeTransformedPosition = function () {
  9621. if (this.parent && this.parent.getWorldMatrix) {
  9622. if (!this.transformedPosition) {
  9623. this.transformedPosition = BABYLON.Vector3.Zero();
  9624. }
  9625. BABYLON.Vector3.TransformCoordinatesToRef(this.getAbsolutePosition(), this.parent.getWorldMatrix(), this.transformedPosition);
  9626. return true;
  9627. }
  9628. return false;
  9629. };
  9630. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9631. if (this.parent && this.parent.getWorldMatrix) {
  9632. this.computeTransformedPosition();
  9633. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9634. return;
  9635. }
  9636. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9637. };
  9638. PointLight.prototype.needCube = function () {
  9639. return true;
  9640. };
  9641. PointLight.prototype.supportsVSM = function () {
  9642. return false;
  9643. };
  9644. PointLight.prototype.needRefreshPerFrame = function () {
  9645. return false;
  9646. };
  9647. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9648. switch (faceIndex) {
  9649. case 0:
  9650. return new BABYLON.Vector3(1, 0, 0);
  9651. case 1:
  9652. return new BABYLON.Vector3(-1, 0, 0);
  9653. case 2:
  9654. return new BABYLON.Vector3(0, -1, 0);
  9655. case 3:
  9656. return new BABYLON.Vector3(0, 1, 0);
  9657. case 4:
  9658. return new BABYLON.Vector3(0, 0, 1);
  9659. case 5:
  9660. return new BABYLON.Vector3(0, 0, -1);
  9661. }
  9662. return BABYLON.Vector3.Zero();
  9663. };
  9664. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9665. var activeCamera = this.getScene().activeCamera;
  9666. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9667. };
  9668. PointLight.prototype._getWorldMatrix = function () {
  9669. if (!this._worldMatrix) {
  9670. this._worldMatrix = BABYLON.Matrix.Identity();
  9671. }
  9672. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9673. return this._worldMatrix;
  9674. };
  9675. PointLight.prototype.getTypeID = function () {
  9676. return 0;
  9677. };
  9678. __decorate([
  9679. BABYLON.serializeAsVector3()
  9680. ], PointLight.prototype, "position", void 0);
  9681. return PointLight;
  9682. })(BABYLON.Light);
  9683. BABYLON.PointLight = PointLight;
  9684. })(BABYLON || (BABYLON = {}));
  9685. var BABYLON;
  9686. (function (BABYLON) {
  9687. var SpotLight = (function (_super) {
  9688. __extends(SpotLight, _super);
  9689. function SpotLight(name, position, direction, angle, exponent, scene) {
  9690. _super.call(this, name, scene);
  9691. this.position = position;
  9692. this.direction = direction;
  9693. this.angle = angle;
  9694. this.exponent = exponent;
  9695. }
  9696. SpotLight.prototype.getAbsolutePosition = function () {
  9697. return this.transformedPosition ? this.transformedPosition : this.position;
  9698. };
  9699. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9700. var activeCamera = this.getScene().activeCamera;
  9701. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9702. };
  9703. SpotLight.prototype.needCube = function () {
  9704. return false;
  9705. };
  9706. SpotLight.prototype.supportsVSM = function () {
  9707. return true;
  9708. };
  9709. SpotLight.prototype.needRefreshPerFrame = function () {
  9710. return false;
  9711. };
  9712. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9713. return this.direction;
  9714. };
  9715. SpotLight.prototype.setDirectionToTarget = function (target) {
  9716. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9717. return this.direction;
  9718. };
  9719. SpotLight.prototype.computeTransformedPosition = function () {
  9720. if (this.parent && this.parent.getWorldMatrix) {
  9721. if (!this.transformedPosition) {
  9722. this.transformedPosition = BABYLON.Vector3.Zero();
  9723. }
  9724. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9725. return true;
  9726. }
  9727. return false;
  9728. };
  9729. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9730. var normalizeDirection;
  9731. if (this.parent && this.parent.getWorldMatrix) {
  9732. if (!this._transformedDirection) {
  9733. this._transformedDirection = BABYLON.Vector3.Zero();
  9734. }
  9735. this.computeTransformedPosition();
  9736. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9737. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9738. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9739. }
  9740. else {
  9741. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9742. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9743. }
  9744. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9745. };
  9746. SpotLight.prototype._getWorldMatrix = function () {
  9747. if (!this._worldMatrix) {
  9748. this._worldMatrix = BABYLON.Matrix.Identity();
  9749. }
  9750. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9751. return this._worldMatrix;
  9752. };
  9753. SpotLight.prototype.getTypeID = function () {
  9754. return 2;
  9755. };
  9756. __decorate([
  9757. BABYLON.serializeAsVector3()
  9758. ], SpotLight.prototype, "position", void 0);
  9759. __decorate([
  9760. BABYLON.serializeAsVector3()
  9761. ], SpotLight.prototype, "direction", void 0);
  9762. __decorate([
  9763. BABYLON.serialize()
  9764. ], SpotLight.prototype, "angle", void 0);
  9765. __decorate([
  9766. BABYLON.serialize()
  9767. ], SpotLight.prototype, "exponent", void 0);
  9768. return SpotLight;
  9769. })(BABYLON.Light);
  9770. BABYLON.SpotLight = SpotLight;
  9771. })(BABYLON || (BABYLON = {}));
  9772. var BABYLON;
  9773. (function (BABYLON) {
  9774. var HemisphericLight = (function (_super) {
  9775. __extends(HemisphericLight, _super);
  9776. function HemisphericLight(name, direction, scene) {
  9777. _super.call(this, name, scene);
  9778. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9779. this.direction = direction;
  9780. }
  9781. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9782. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9783. return this.direction;
  9784. };
  9785. HemisphericLight.prototype.getShadowGenerator = function () {
  9786. return null;
  9787. };
  9788. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9789. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9790. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9791. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9792. };
  9793. HemisphericLight.prototype._getWorldMatrix = function () {
  9794. if (!this._worldMatrix) {
  9795. this._worldMatrix = BABYLON.Matrix.Identity();
  9796. }
  9797. return this._worldMatrix;
  9798. };
  9799. HemisphericLight.prototype.getTypeID = function () {
  9800. return 3;
  9801. };
  9802. __decorate([
  9803. BABYLON.serializeAsColor3()
  9804. ], HemisphericLight.prototype, "groundColor", void 0);
  9805. __decorate([
  9806. BABYLON.serializeAsVector3()
  9807. ], HemisphericLight.prototype, "direction", void 0);
  9808. return HemisphericLight;
  9809. })(BABYLON.Light);
  9810. BABYLON.HemisphericLight = HemisphericLight;
  9811. })(BABYLON || (BABYLON = {}));
  9812. var BABYLON;
  9813. (function (BABYLON) {
  9814. var DirectionalLight = (function (_super) {
  9815. __extends(DirectionalLight, _super);
  9816. function DirectionalLight(name, direction, scene) {
  9817. _super.call(this, name, scene);
  9818. this.shadowOrthoScale = 0.5;
  9819. this.autoUpdateExtends = true;
  9820. // Cache
  9821. this._orthoLeft = Number.MAX_VALUE;
  9822. this._orthoRight = Number.MIN_VALUE;
  9823. this._orthoTop = Number.MIN_VALUE;
  9824. this._orthoBottom = Number.MAX_VALUE;
  9825. this.position = direction.scale(-1);
  9826. this.direction = direction;
  9827. }
  9828. DirectionalLight.prototype.getAbsolutePosition = function () {
  9829. return this.transformedPosition ? this.transformedPosition : this.position;
  9830. };
  9831. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9832. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9833. return this.direction;
  9834. };
  9835. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9836. var activeCamera = this.getScene().activeCamera;
  9837. // Check extends
  9838. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9839. var tempVector3 = BABYLON.Vector3.Zero();
  9840. this._orthoLeft = Number.MAX_VALUE;
  9841. this._orthoRight = Number.MIN_VALUE;
  9842. this._orthoTop = Number.MIN_VALUE;
  9843. this._orthoBottom = Number.MAX_VALUE;
  9844. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9845. var mesh = renderList[meshIndex];
  9846. if (!mesh) {
  9847. continue;
  9848. }
  9849. var boundingInfo = mesh.getBoundingInfo();
  9850. if (!boundingInfo) {
  9851. continue;
  9852. }
  9853. var boundingBox = boundingInfo.boundingBox;
  9854. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9855. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9856. if (tempVector3.x < this._orthoLeft)
  9857. this._orthoLeft = tempVector3.x;
  9858. if (tempVector3.y < this._orthoBottom)
  9859. this._orthoBottom = tempVector3.y;
  9860. if (tempVector3.x > this._orthoRight)
  9861. this._orthoRight = tempVector3.x;
  9862. if (tempVector3.y > this._orthoTop)
  9863. this._orthoTop = tempVector3.y;
  9864. }
  9865. }
  9866. }
  9867. var xOffset = this._orthoRight - this._orthoLeft;
  9868. var yOffset = this._orthoTop - this._orthoBottom;
  9869. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  9870. };
  9871. DirectionalLight.prototype.supportsVSM = function () {
  9872. return true;
  9873. };
  9874. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9875. return true;
  9876. };
  9877. DirectionalLight.prototype.needCube = function () {
  9878. return false;
  9879. };
  9880. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9881. return this.direction;
  9882. };
  9883. DirectionalLight.prototype.computeTransformedPosition = function () {
  9884. if (this.parent && this.parent.getWorldMatrix) {
  9885. if (!this.transformedPosition) {
  9886. this.transformedPosition = BABYLON.Vector3.Zero();
  9887. }
  9888. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9889. return true;
  9890. }
  9891. return false;
  9892. };
  9893. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9894. if (this.parent && this.parent.getWorldMatrix) {
  9895. if (!this._transformedDirection) {
  9896. this._transformedDirection = BABYLON.Vector3.Zero();
  9897. }
  9898. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9899. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9900. return;
  9901. }
  9902. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9903. };
  9904. DirectionalLight.prototype._getWorldMatrix = function () {
  9905. if (!this._worldMatrix) {
  9906. this._worldMatrix = BABYLON.Matrix.Identity();
  9907. }
  9908. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9909. return this._worldMatrix;
  9910. };
  9911. DirectionalLight.prototype.getTypeID = function () {
  9912. return 1;
  9913. };
  9914. __decorate([
  9915. BABYLON.serializeAsVector3()
  9916. ], DirectionalLight.prototype, "position", void 0);
  9917. __decorate([
  9918. BABYLON.serializeAsVector3()
  9919. ], DirectionalLight.prototype, "direction", void 0);
  9920. __decorate([
  9921. BABYLON.serialize()
  9922. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9923. __decorate([
  9924. BABYLON.serialize()
  9925. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9926. return DirectionalLight;
  9927. })(BABYLON.Light);
  9928. BABYLON.DirectionalLight = DirectionalLight;
  9929. })(BABYLON || (BABYLON = {}));
  9930. var BABYLON;
  9931. (function (BABYLON) {
  9932. var ShadowGenerator = (function () {
  9933. function ShadowGenerator(mapSize, light) {
  9934. var _this = this;
  9935. // Members
  9936. this._filter = ShadowGenerator.FILTER_NONE;
  9937. this.blurScale = 2;
  9938. this._blurBoxOffset = 0;
  9939. this._bias = 0.00005;
  9940. this._lightDirection = BABYLON.Vector3.Zero();
  9941. this.forceBackFacesOnly = false;
  9942. this._darkness = 0;
  9943. this._transparencyShadow = false;
  9944. this._viewMatrix = BABYLON.Matrix.Zero();
  9945. this._projectionMatrix = BABYLON.Matrix.Zero();
  9946. this._transformMatrix = BABYLON.Matrix.Zero();
  9947. this._worldViewProjection = BABYLON.Matrix.Zero();
  9948. this._currentFaceIndex = 0;
  9949. this._currentFaceIndexCache = 0;
  9950. this._light = light;
  9951. this._scene = light.getScene();
  9952. this._mapSize = mapSize;
  9953. light._shadowGenerator = this;
  9954. // Render target
  9955. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9956. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9957. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9958. this._shadowMap.anisotropicFilteringLevel = 1;
  9959. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9960. this._shadowMap.renderParticles = false;
  9961. this._shadowMap.onBeforeRender = function (faceIndex) {
  9962. _this._currentFaceIndex = faceIndex;
  9963. };
  9964. this._shadowMap.onAfterUnbind = function () {
  9965. if (!_this.useBlurVarianceShadowMap) {
  9966. return;
  9967. }
  9968. if (!_this._shadowMap2) {
  9969. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9970. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9971. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9972. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9973. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9974. _this._downSamplePostprocess.onApply = function (effect) {
  9975. effect.setTexture("textureSampler", _this._shadowMap);
  9976. };
  9977. _this.blurBoxOffset = 1;
  9978. }
  9979. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9980. };
  9981. // Custom render function
  9982. var renderSubMesh = function (subMesh) {
  9983. var mesh = subMesh.getRenderingMesh();
  9984. var scene = _this._scene;
  9985. var engine = scene.getEngine();
  9986. // Culling
  9987. engine.setState(subMesh.getMaterial().backFaceCulling);
  9988. // Managing instances
  9989. var batch = mesh._getInstancesRenderList(subMesh._id);
  9990. if (batch.mustReturn) {
  9991. return;
  9992. }
  9993. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9994. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9995. engine.enableEffect(_this._effect);
  9996. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9997. var material = subMesh.getMaterial();
  9998. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9999. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10000. if (_this.getLight().needCube()) {
  10001. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10002. }
  10003. // Alpha test
  10004. if (material && material.needAlphaTesting()) {
  10005. var alphaTexture = material.getAlphaTestTexture();
  10006. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10007. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10008. }
  10009. // Bones
  10010. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10011. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10012. }
  10013. if (_this.forceBackFacesOnly) {
  10014. engine.setState(true, 0, false, true);
  10015. }
  10016. // Draw
  10017. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10018. if (_this.forceBackFacesOnly) {
  10019. engine.setState(true, 0, false, false);
  10020. }
  10021. }
  10022. else {
  10023. // Need to reset refresh rate of the shadowMap
  10024. _this._shadowMap.resetRefreshCounter();
  10025. }
  10026. };
  10027. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10028. var index;
  10029. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10030. renderSubMesh(opaqueSubMeshes.data[index]);
  10031. }
  10032. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10033. renderSubMesh(alphaTestSubMeshes.data[index]);
  10034. }
  10035. if (_this._transparencyShadow) {
  10036. for (index = 0; index < transparentSubMeshes.length; index++) {
  10037. renderSubMesh(transparentSubMeshes.data[index]);
  10038. }
  10039. }
  10040. };
  10041. this._shadowMap.onClear = function (engine) {
  10042. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10043. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10044. }
  10045. else {
  10046. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10047. }
  10048. };
  10049. }
  10050. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10051. // Static
  10052. get: function () {
  10053. return ShadowGenerator._FILTER_NONE;
  10054. },
  10055. enumerable: true,
  10056. configurable: true
  10057. });
  10058. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10059. get: function () {
  10060. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10066. get: function () {
  10067. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10068. },
  10069. enumerable: true,
  10070. configurable: true
  10071. });
  10072. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10073. get: function () {
  10074. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10080. get: function () {
  10081. return this._bias;
  10082. },
  10083. set: function (bias) {
  10084. this._bias = bias;
  10085. },
  10086. enumerable: true,
  10087. configurable: true
  10088. });
  10089. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10090. get: function () {
  10091. return this._blurBoxOffset;
  10092. },
  10093. set: function (value) {
  10094. var _this = this;
  10095. if (this._blurBoxOffset === value) {
  10096. return;
  10097. }
  10098. this._blurBoxOffset = value;
  10099. if (this._boxBlurPostprocess) {
  10100. this._boxBlurPostprocess.dispose();
  10101. }
  10102. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  10103. this._boxBlurPostprocess.onApply = function (effect) {
  10104. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10105. };
  10106. },
  10107. enumerable: true,
  10108. configurable: true
  10109. });
  10110. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10111. get: function () {
  10112. return this._filter;
  10113. },
  10114. set: function (value) {
  10115. if (this._filter === value) {
  10116. return;
  10117. }
  10118. this._filter = value;
  10119. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10120. this._shadowMap.anisotropicFilteringLevel = 16;
  10121. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10122. }
  10123. else {
  10124. this._shadowMap.anisotropicFilteringLevel = 1;
  10125. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10126. }
  10127. },
  10128. enumerable: true,
  10129. configurable: true
  10130. });
  10131. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10132. get: function () {
  10133. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10134. },
  10135. set: function (value) {
  10136. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10137. },
  10138. enumerable: true,
  10139. configurable: true
  10140. });
  10141. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10142. get: function () {
  10143. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10144. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10145. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10146. },
  10147. set: function (value) {
  10148. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10149. },
  10150. enumerable: true,
  10151. configurable: true
  10152. });
  10153. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10154. get: function () {
  10155. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10156. },
  10157. set: function (value) {
  10158. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10159. },
  10160. enumerable: true,
  10161. configurable: true
  10162. });
  10163. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10164. var defines = [];
  10165. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10166. defines.push("#define VSM");
  10167. }
  10168. if (this.getLight().needCube()) {
  10169. defines.push("#define CUBEMAP");
  10170. }
  10171. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10172. var mesh = subMesh.getMesh();
  10173. var material = subMesh.getMaterial();
  10174. // Alpha test
  10175. if (material && material.needAlphaTesting()) {
  10176. defines.push("#define ALPHATEST");
  10177. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10178. attribs.push(BABYLON.VertexBuffer.UVKind);
  10179. defines.push("#define UV1");
  10180. }
  10181. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10182. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10183. defines.push("#define UV2");
  10184. }
  10185. }
  10186. // Bones
  10187. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10188. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10189. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10190. if (mesh.numBoneInfluencers > 4) {
  10191. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10192. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10193. }
  10194. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10195. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10196. }
  10197. else {
  10198. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10199. }
  10200. // Instances
  10201. if (useInstances) {
  10202. defines.push("#define INSTANCES");
  10203. attribs.push("world0");
  10204. attribs.push("world1");
  10205. attribs.push("world2");
  10206. attribs.push("world3");
  10207. }
  10208. // Get correct effect
  10209. var join = defines.join("\n");
  10210. if (this._cachedDefines !== join) {
  10211. this._cachedDefines = join;
  10212. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10213. }
  10214. return this._effect.isReady();
  10215. };
  10216. ShadowGenerator.prototype.getShadowMap = function () {
  10217. return this._shadowMap;
  10218. };
  10219. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10220. if (this._shadowMap2) {
  10221. return this._shadowMap2;
  10222. }
  10223. return this._shadowMap;
  10224. };
  10225. ShadowGenerator.prototype.getLight = function () {
  10226. return this._light;
  10227. };
  10228. // Methods
  10229. ShadowGenerator.prototype.getTransformMatrix = function () {
  10230. var scene = this._scene;
  10231. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10232. return this._transformMatrix;
  10233. }
  10234. this._currentRenderID = scene.getRenderId();
  10235. this._currentFaceIndexCache = this._currentFaceIndex;
  10236. var lightPosition = this._light.position;
  10237. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10238. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10239. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10240. }
  10241. if (this._light.computeTransformedPosition()) {
  10242. lightPosition = this._light.transformedPosition;
  10243. }
  10244. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10245. this._cachedPosition = lightPosition.clone();
  10246. this._cachedDirection = this._lightDirection.clone();
  10247. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10248. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10249. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10250. }
  10251. return this._transformMatrix;
  10252. };
  10253. ShadowGenerator.prototype.getDarkness = function () {
  10254. return this._darkness;
  10255. };
  10256. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10257. if (darkness >= 1.0)
  10258. this._darkness = 1.0;
  10259. else if (darkness <= 0.0)
  10260. this._darkness = 0.0;
  10261. else
  10262. this._darkness = darkness;
  10263. };
  10264. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10265. this._transparencyShadow = hasShadow;
  10266. };
  10267. ShadowGenerator.prototype._packHalf = function (depth) {
  10268. var scale = depth * 255.0;
  10269. var fract = scale - Math.floor(scale);
  10270. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10271. };
  10272. ShadowGenerator.prototype.dispose = function () {
  10273. this._shadowMap.dispose();
  10274. if (this._shadowMap2) {
  10275. this._shadowMap2.dispose();
  10276. }
  10277. if (this._downSamplePostprocess) {
  10278. this._downSamplePostprocess.dispose();
  10279. }
  10280. if (this._boxBlurPostprocess) {
  10281. this._boxBlurPostprocess.dispose();
  10282. }
  10283. };
  10284. ShadowGenerator.prototype.serialize = function () {
  10285. var serializationObject = {};
  10286. serializationObject.lightId = this._light.id;
  10287. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10288. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10289. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10290. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10291. serializationObject.renderList = [];
  10292. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10293. var mesh = this.getShadowMap().renderList[meshIndex];
  10294. serializationObject.renderList.push(mesh.id);
  10295. }
  10296. return serializationObject;
  10297. };
  10298. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10299. //casting to point light, as light is missing the position attr and typescript complains.
  10300. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10301. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10302. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10303. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  10304. meshes.forEach(function (mesh) {
  10305. shadowGenerator.getShadowMap().renderList.push(mesh);
  10306. });
  10307. }
  10308. if (parsedShadowGenerator.usePoissonSampling) {
  10309. shadowGenerator.usePoissonSampling = true;
  10310. }
  10311. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10312. shadowGenerator.useVarianceShadowMap = true;
  10313. }
  10314. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10315. shadowGenerator.useBlurVarianceShadowMap = true;
  10316. if (parsedShadowGenerator.blurScale) {
  10317. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10318. }
  10319. if (parsedShadowGenerator.blurBoxOffset) {
  10320. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10321. }
  10322. }
  10323. if (parsedShadowGenerator.bias !== undefined) {
  10324. shadowGenerator.bias = parsedShadowGenerator.bias;
  10325. }
  10326. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10327. return shadowGenerator;
  10328. };
  10329. ShadowGenerator._FILTER_NONE = 0;
  10330. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10331. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10332. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10333. return ShadowGenerator;
  10334. })();
  10335. BABYLON.ShadowGenerator = ShadowGenerator;
  10336. })(BABYLON || (BABYLON = {}));
  10337. var BABYLON;
  10338. (function (BABYLON) {
  10339. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10340. if (boxMin.x > sphereCenter.x + sphereRadius)
  10341. return false;
  10342. if (sphereCenter.x - sphereRadius > boxMax.x)
  10343. return false;
  10344. if (boxMin.y > sphereCenter.y + sphereRadius)
  10345. return false;
  10346. if (sphereCenter.y - sphereRadius > boxMax.y)
  10347. return false;
  10348. if (boxMin.z > sphereCenter.z + sphereRadius)
  10349. return false;
  10350. if (sphereCenter.z - sphereRadius > boxMax.z)
  10351. return false;
  10352. return true;
  10353. };
  10354. var getLowestRoot = function (a, b, c, maxR) {
  10355. var determinant = b * b - 4.0 * a * c;
  10356. var result = { root: 0, found: false };
  10357. if (determinant < 0)
  10358. return result;
  10359. var sqrtD = Math.sqrt(determinant);
  10360. var r1 = (-b - sqrtD) / (2.0 * a);
  10361. var r2 = (-b + sqrtD) / (2.0 * a);
  10362. if (r1 > r2) {
  10363. var temp = r2;
  10364. r2 = r1;
  10365. r1 = temp;
  10366. }
  10367. if (r1 > 0 && r1 < maxR) {
  10368. result.root = r1;
  10369. result.found = true;
  10370. return result;
  10371. }
  10372. if (r2 > 0 && r2 < maxR) {
  10373. result.root = r2;
  10374. result.found = true;
  10375. return result;
  10376. }
  10377. return result;
  10378. };
  10379. var Collider = (function () {
  10380. function Collider() {
  10381. this.radius = new BABYLON.Vector3(1, 1, 1);
  10382. this.retry = 0;
  10383. this.basePointWorld = BABYLON.Vector3.Zero();
  10384. this.velocityWorld = BABYLON.Vector3.Zero();
  10385. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10386. this._collisionPoint = BABYLON.Vector3.Zero();
  10387. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10388. this._tempVector = BABYLON.Vector3.Zero();
  10389. this._tempVector2 = BABYLON.Vector3.Zero();
  10390. this._tempVector3 = BABYLON.Vector3.Zero();
  10391. this._tempVector4 = BABYLON.Vector3.Zero();
  10392. this._edge = BABYLON.Vector3.Zero();
  10393. this._baseToVertex = BABYLON.Vector3.Zero();
  10394. this._destinationPoint = BABYLON.Vector3.Zero();
  10395. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10396. this._displacementVector = BABYLON.Vector3.Zero();
  10397. }
  10398. // Methods
  10399. Collider.prototype._initialize = function (source, dir, e) {
  10400. this.velocity = dir;
  10401. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10402. this.basePoint = source;
  10403. source.multiplyToRef(this.radius, this.basePointWorld);
  10404. dir.multiplyToRef(this.radius, this.velocityWorld);
  10405. this.velocityWorldLength = this.velocityWorld.length();
  10406. this.epsilon = e;
  10407. this.collisionFound = false;
  10408. };
  10409. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10410. pa.subtractToRef(point, this._tempVector);
  10411. pb.subtractToRef(point, this._tempVector2);
  10412. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10413. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10414. if (d < 0)
  10415. return false;
  10416. pc.subtractToRef(point, this._tempVector3);
  10417. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10418. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10419. if (d < 0)
  10420. return false;
  10421. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10422. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10423. return d >= 0;
  10424. };
  10425. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10426. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10427. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10428. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10429. return false;
  10430. }
  10431. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10432. return false;
  10433. return true;
  10434. };
  10435. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10436. var t0;
  10437. var embeddedInPlane = false;
  10438. //defensive programming, actually not needed.
  10439. if (!trianglePlaneArray) {
  10440. trianglePlaneArray = [];
  10441. }
  10442. if (!trianglePlaneArray[faceIndex]) {
  10443. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10444. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10445. }
  10446. var trianglePlane = trianglePlaneArray[faceIndex];
  10447. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10448. return;
  10449. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10450. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10451. if (normalDotVelocity == 0) {
  10452. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10453. return;
  10454. embeddedInPlane = true;
  10455. t0 = 0;
  10456. }
  10457. else {
  10458. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10459. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10460. if (t0 > t1) {
  10461. var temp = t1;
  10462. t1 = t0;
  10463. t0 = temp;
  10464. }
  10465. if (t0 > 1.0 || t1 < 0.0)
  10466. return;
  10467. if (t0 < 0)
  10468. t0 = 0;
  10469. if (t0 > 1.0)
  10470. t0 = 1.0;
  10471. }
  10472. this._collisionPoint.copyFromFloats(0, 0, 0);
  10473. var found = false;
  10474. var t = 1.0;
  10475. if (!embeddedInPlane) {
  10476. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10477. this.velocity.scaleToRef(t0, this._tempVector);
  10478. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10479. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10480. found = true;
  10481. t = t0;
  10482. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10483. }
  10484. }
  10485. if (!found) {
  10486. var velocitySquaredLength = this.velocity.lengthSquared();
  10487. var a = velocitySquaredLength;
  10488. this.basePoint.subtractToRef(p1, this._tempVector);
  10489. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10490. var c = this._tempVector.lengthSquared() - 1.0;
  10491. var lowestRoot = getLowestRoot(a, b, c, t);
  10492. if (lowestRoot.found) {
  10493. t = lowestRoot.root;
  10494. found = true;
  10495. this._collisionPoint.copyFrom(p1);
  10496. }
  10497. this.basePoint.subtractToRef(p2, this._tempVector);
  10498. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10499. c = this._tempVector.lengthSquared() - 1.0;
  10500. lowestRoot = getLowestRoot(a, b, c, t);
  10501. if (lowestRoot.found) {
  10502. t = lowestRoot.root;
  10503. found = true;
  10504. this._collisionPoint.copyFrom(p2);
  10505. }
  10506. this.basePoint.subtractToRef(p3, this._tempVector);
  10507. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10508. c = this._tempVector.lengthSquared() - 1.0;
  10509. lowestRoot = getLowestRoot(a, b, c, t);
  10510. if (lowestRoot.found) {
  10511. t = lowestRoot.root;
  10512. found = true;
  10513. this._collisionPoint.copyFrom(p3);
  10514. }
  10515. p2.subtractToRef(p1, this._edge);
  10516. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10517. var edgeSquaredLength = this._edge.lengthSquared();
  10518. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10519. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10520. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10521. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10522. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10523. lowestRoot = getLowestRoot(a, b, c, t);
  10524. if (lowestRoot.found) {
  10525. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10526. if (f >= 0.0 && f <= 1.0) {
  10527. t = lowestRoot.root;
  10528. found = true;
  10529. this._edge.scaleInPlace(f);
  10530. p1.addToRef(this._edge, this._collisionPoint);
  10531. }
  10532. }
  10533. p3.subtractToRef(p2, this._edge);
  10534. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10535. edgeSquaredLength = this._edge.lengthSquared();
  10536. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10537. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10538. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10539. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10540. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10541. lowestRoot = getLowestRoot(a, b, c, t);
  10542. if (lowestRoot.found) {
  10543. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10544. if (f >= 0.0 && f <= 1.0) {
  10545. t = lowestRoot.root;
  10546. found = true;
  10547. this._edge.scaleInPlace(f);
  10548. p2.addToRef(this._edge, this._collisionPoint);
  10549. }
  10550. }
  10551. p1.subtractToRef(p3, this._edge);
  10552. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10553. edgeSquaredLength = this._edge.lengthSquared();
  10554. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10555. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10556. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10557. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10558. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10559. lowestRoot = getLowestRoot(a, b, c, t);
  10560. if (lowestRoot.found) {
  10561. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10562. if (f >= 0.0 && f <= 1.0) {
  10563. t = lowestRoot.root;
  10564. found = true;
  10565. this._edge.scaleInPlace(f);
  10566. p3.addToRef(this._edge, this._collisionPoint);
  10567. }
  10568. }
  10569. }
  10570. if (found) {
  10571. var distToCollision = t * this.velocity.length();
  10572. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10573. if (!this.intersectionPoint) {
  10574. this.intersectionPoint = this._collisionPoint.clone();
  10575. }
  10576. else {
  10577. this.intersectionPoint.copyFrom(this._collisionPoint);
  10578. }
  10579. this.nearestDistance = distToCollision;
  10580. this.collisionFound = true;
  10581. }
  10582. }
  10583. };
  10584. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10585. for (var i = indexStart; i < indexEnd; i += 3) {
  10586. var p1 = pts[indices[i] - decal];
  10587. var p2 = pts[indices[i + 1] - decal];
  10588. var p3 = pts[indices[i + 2] - decal];
  10589. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10590. }
  10591. };
  10592. Collider.prototype._getResponse = function (pos, vel) {
  10593. pos.addToRef(vel, this._destinationPoint);
  10594. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10595. this.basePoint.addToRef(vel, pos);
  10596. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10597. this._slidePlaneNormal.normalize();
  10598. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10599. pos.addInPlace(this._displacementVector);
  10600. this.intersectionPoint.addInPlace(this._displacementVector);
  10601. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10602. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10603. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10604. };
  10605. return Collider;
  10606. })();
  10607. BABYLON.Collider = Collider;
  10608. })(BABYLON || (BABYLON = {}));
  10609. var BABYLON;
  10610. (function (BABYLON) {
  10611. //WebWorker code will be inserted to this variable.
  10612. BABYLON.CollisionWorker = "";
  10613. (function (WorkerTaskType) {
  10614. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10615. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10616. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10617. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10618. var WorkerTaskType = BABYLON.WorkerTaskType;
  10619. (function (WorkerReplyType) {
  10620. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10621. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10622. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10623. var WorkerReplyType = BABYLON.WorkerReplyType;
  10624. var CollisionCoordinatorWorker = (function () {
  10625. function CollisionCoordinatorWorker() {
  10626. var _this = this;
  10627. this._scaledPosition = BABYLON.Vector3.Zero();
  10628. this._scaledVelocity = BABYLON.Vector3.Zero();
  10629. this.onMeshUpdated = function (mesh) {
  10630. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10631. };
  10632. this.onGeometryUpdated = function (geometry) {
  10633. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10634. };
  10635. this._afterRender = function () {
  10636. if (!_this._init)
  10637. return;
  10638. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10639. return;
  10640. }
  10641. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10642. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10643. if (_this._runningUpdated > 4) {
  10644. return;
  10645. }
  10646. ++_this._runningUpdated;
  10647. var payload = {
  10648. updatedMeshes: _this._addUpdateMeshesList,
  10649. updatedGeometries: _this._addUpdateGeometriesList,
  10650. removedGeometries: _this._toRemoveGeometryArray,
  10651. removedMeshes: _this._toRemoveMeshesArray
  10652. };
  10653. var message = {
  10654. payload: payload,
  10655. taskType: WorkerTaskType.UPDATE
  10656. };
  10657. var serializable = [];
  10658. for (var id in payload.updatedGeometries) {
  10659. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10660. //prepare transferables
  10661. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10662. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10663. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10664. }
  10665. }
  10666. _this._worker.postMessage(message, serializable);
  10667. _this._addUpdateMeshesList = {};
  10668. _this._addUpdateGeometriesList = {};
  10669. _this._toRemoveGeometryArray = [];
  10670. _this._toRemoveMeshesArray = [];
  10671. };
  10672. this._onMessageFromWorker = function (e) {
  10673. var returnData = e.data;
  10674. if (returnData.error != WorkerReplyType.SUCCESS) {
  10675. //TODO what errors can be returned from the worker?
  10676. BABYLON.Tools.Warn("error returned from worker!");
  10677. return;
  10678. }
  10679. switch (returnData.taskType) {
  10680. case WorkerTaskType.INIT:
  10681. _this._init = true;
  10682. //Update the worked with ALL of the scene's current state
  10683. _this._scene.meshes.forEach(function (mesh) {
  10684. _this.onMeshAdded(mesh);
  10685. });
  10686. _this._scene.getGeometries().forEach(function (geometry) {
  10687. _this.onGeometryAdded(geometry);
  10688. });
  10689. break;
  10690. case WorkerTaskType.UPDATE:
  10691. _this._runningUpdated--;
  10692. break;
  10693. case WorkerTaskType.COLLIDE:
  10694. _this._runningCollisionTask = false;
  10695. var returnPayload = returnData.payload;
  10696. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10697. return;
  10698. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10699. //cleanup
  10700. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10701. break;
  10702. }
  10703. };
  10704. this._collisionsCallbackArray = [];
  10705. this._init = false;
  10706. this._runningUpdated = 0;
  10707. this._runningCollisionTask = false;
  10708. this._addUpdateMeshesList = {};
  10709. this._addUpdateGeometriesList = {};
  10710. this._toRemoveGeometryArray = [];
  10711. this._toRemoveMeshesArray = [];
  10712. }
  10713. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10714. if (!this._init)
  10715. return;
  10716. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10717. return;
  10718. position.divideToRef(collider.radius, this._scaledPosition);
  10719. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10720. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10721. var payload = {
  10722. collider: {
  10723. position: this._scaledPosition.asArray(),
  10724. velocity: this._scaledVelocity.asArray(),
  10725. radius: collider.radius.asArray()
  10726. },
  10727. collisionId: collisionIndex,
  10728. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10729. maximumRetry: maximumRetry
  10730. };
  10731. var message = {
  10732. payload: payload,
  10733. taskType: WorkerTaskType.COLLIDE
  10734. };
  10735. this._worker.postMessage(message);
  10736. };
  10737. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10738. this._scene = scene;
  10739. this._scene.registerAfterRender(this._afterRender);
  10740. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10741. this._worker = new Worker(workerUrl);
  10742. this._worker.onmessage = this._onMessageFromWorker;
  10743. var message = {
  10744. payload: {},
  10745. taskType: WorkerTaskType.INIT
  10746. };
  10747. this._worker.postMessage(message);
  10748. };
  10749. CollisionCoordinatorWorker.prototype.destroy = function () {
  10750. this._scene.unregisterAfterRender(this._afterRender);
  10751. this._worker.terminate();
  10752. };
  10753. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10754. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10755. this.onMeshUpdated(mesh);
  10756. };
  10757. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10758. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10759. };
  10760. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10761. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10762. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10763. this.onGeometryUpdated(geometry);
  10764. };
  10765. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10766. this._toRemoveGeometryArray.push(geometry.id);
  10767. };
  10768. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10769. var submeshes = [];
  10770. if (mesh.subMeshes) {
  10771. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10772. return {
  10773. position: idx,
  10774. verticesStart: sm.verticesStart,
  10775. verticesCount: sm.verticesCount,
  10776. indexStart: sm.indexStart,
  10777. indexCount: sm.indexCount,
  10778. hasMaterial: !!sm.getMaterial(),
  10779. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10780. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10781. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10782. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10783. };
  10784. });
  10785. }
  10786. var geometryId = null;
  10787. if (mesh instanceof BABYLON.Mesh) {
  10788. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10789. }
  10790. else if (mesh instanceof BABYLON.InstancedMesh) {
  10791. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10792. }
  10793. return {
  10794. uniqueId: mesh.uniqueId,
  10795. id: mesh.id,
  10796. name: mesh.name,
  10797. geometryId: geometryId,
  10798. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10799. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10800. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10801. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10802. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10803. subMeshes: submeshes,
  10804. checkCollisions: mesh.checkCollisions
  10805. };
  10806. };
  10807. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10808. return {
  10809. id: geometry.id,
  10810. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10811. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10812. indices: new Int32Array(geometry.getIndices() || []),
  10813. };
  10814. };
  10815. return CollisionCoordinatorWorker;
  10816. })();
  10817. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10818. var CollisionCoordinatorLegacy = (function () {
  10819. function CollisionCoordinatorLegacy() {
  10820. this._scaledPosition = BABYLON.Vector3.Zero();
  10821. this._scaledVelocity = BABYLON.Vector3.Zero();
  10822. this._finalPosition = BABYLON.Vector3.Zero();
  10823. }
  10824. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10825. position.divideToRef(collider.radius, this._scaledPosition);
  10826. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10827. collider.collidedMesh = null;
  10828. collider.retry = 0;
  10829. collider.initialVelocity = this._scaledVelocity;
  10830. collider.initialPosition = this._scaledPosition;
  10831. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10832. this._finalPosition.multiplyInPlace(collider.radius);
  10833. //run the callback
  10834. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10835. };
  10836. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10837. this._scene = scene;
  10838. };
  10839. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10840. //Legacy need no destruction method.
  10841. };
  10842. //No update in legacy mode
  10843. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10844. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10845. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10846. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10847. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10848. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10849. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10850. if (excludedMesh === void 0) { excludedMesh = null; }
  10851. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10852. if (collider.retry >= maximumRetry) {
  10853. finalPosition.copyFrom(position);
  10854. return;
  10855. }
  10856. collider._initialize(position, velocity, closeDistance);
  10857. // Check all meshes
  10858. for (var index = 0; index < this._scene.meshes.length; index++) {
  10859. var mesh = this._scene.meshes[index];
  10860. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10861. mesh._checkCollision(collider);
  10862. }
  10863. }
  10864. if (!collider.collisionFound) {
  10865. position.addToRef(velocity, finalPosition);
  10866. return;
  10867. }
  10868. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10869. collider._getResponse(position, velocity);
  10870. }
  10871. if (velocity.length() <= closeDistance) {
  10872. finalPosition.copyFrom(position);
  10873. return;
  10874. }
  10875. collider.retry++;
  10876. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10877. };
  10878. return CollisionCoordinatorLegacy;
  10879. })();
  10880. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10881. })(BABYLON || (BABYLON = {}));
  10882. var BABYLON;
  10883. (function (BABYLON) {
  10884. var Camera = (function (_super) {
  10885. __extends(Camera, _super);
  10886. function Camera(name, position, scene) {
  10887. _super.call(this, name, scene);
  10888. this.upVector = BABYLON.Vector3.Up();
  10889. this.orthoLeft = null;
  10890. this.orthoRight = null;
  10891. this.orthoBottom = null;
  10892. this.orthoTop = null;
  10893. this.fov = 0.8;
  10894. this.minZ = 1.0;
  10895. this.maxZ = 10000.0;
  10896. this.inertia = 0.9;
  10897. this.mode = Camera.PERSPECTIVE_CAMERA;
  10898. this.isIntermediate = false;
  10899. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10900. this.layerMask = 0x0FFFFFFF;
  10901. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10902. // Camera rig members
  10903. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10904. this._rigCameras = new Array();
  10905. // Cache
  10906. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10907. this._projectionMatrix = new BABYLON.Matrix();
  10908. this._postProcesses = new Array();
  10909. this._postProcessesTakenIndices = [];
  10910. this._activeMeshes = new BABYLON.SmartArray(256);
  10911. this._globalPosition = BABYLON.Vector3.Zero();
  10912. scene.addCamera(this);
  10913. if (!scene.activeCamera) {
  10914. scene.activeCamera = this;
  10915. }
  10916. this.position = position;
  10917. }
  10918. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10919. get: function () {
  10920. return Camera._PERSPECTIVE_CAMERA;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10926. get: function () {
  10927. return Camera._ORTHOGRAPHIC_CAMERA;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10933. get: function () {
  10934. return Camera._FOVMODE_VERTICAL_FIXED;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10940. get: function () {
  10941. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10947. get: function () {
  10948. return Camera._RIG_MODE_NONE;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10954. get: function () {
  10955. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10961. get: function () {
  10962. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10963. },
  10964. enumerable: true,
  10965. configurable: true
  10966. });
  10967. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10968. get: function () {
  10969. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10975. get: function () {
  10976. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10982. get: function () {
  10983. return Camera._RIG_MODE_VR;
  10984. },
  10985. enumerable: true,
  10986. configurable: true
  10987. });
  10988. /**
  10989. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10990. */
  10991. Camera.prototype.toString = function (fullDetails) {
  10992. var ret = "Name: " + this.name;
  10993. ret += ", type: " + this.getTypeName();
  10994. if (this.animations) {
  10995. for (var i = 0; i < this.animations.length; i++) {
  10996. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10997. }
  10998. }
  10999. if (fullDetails) {
  11000. }
  11001. return ret;
  11002. };
  11003. Object.defineProperty(Camera.prototype, "globalPosition", {
  11004. get: function () {
  11005. return this._globalPosition;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Camera.prototype.getActiveMeshes = function () {
  11011. return this._activeMeshes;
  11012. };
  11013. Camera.prototype.isActiveMesh = function (mesh) {
  11014. return (this._activeMeshes.indexOf(mesh) !== -1);
  11015. };
  11016. //Cache
  11017. Camera.prototype._initCache = function () {
  11018. _super.prototype._initCache.call(this);
  11019. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11020. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11021. this._cache.mode = undefined;
  11022. this._cache.minZ = undefined;
  11023. this._cache.maxZ = undefined;
  11024. this._cache.fov = undefined;
  11025. this._cache.aspectRatio = undefined;
  11026. this._cache.orthoLeft = undefined;
  11027. this._cache.orthoRight = undefined;
  11028. this._cache.orthoBottom = undefined;
  11029. this._cache.orthoTop = undefined;
  11030. this._cache.renderWidth = undefined;
  11031. this._cache.renderHeight = undefined;
  11032. };
  11033. Camera.prototype._updateCache = function (ignoreParentClass) {
  11034. if (!ignoreParentClass) {
  11035. _super.prototype._updateCache.call(this);
  11036. }
  11037. var engine = this.getEngine();
  11038. this._cache.position.copyFrom(this.position);
  11039. this._cache.upVector.copyFrom(this.upVector);
  11040. this._cache.mode = this.mode;
  11041. this._cache.minZ = this.minZ;
  11042. this._cache.maxZ = this.maxZ;
  11043. this._cache.fov = this.fov;
  11044. this._cache.aspectRatio = engine.getAspectRatio(this);
  11045. this._cache.orthoLeft = this.orthoLeft;
  11046. this._cache.orthoRight = this.orthoRight;
  11047. this._cache.orthoBottom = this.orthoBottom;
  11048. this._cache.orthoTop = this.orthoTop;
  11049. this._cache.renderWidth = engine.getRenderWidth();
  11050. this._cache.renderHeight = engine.getRenderHeight();
  11051. };
  11052. Camera.prototype._updateFromScene = function () {
  11053. this.updateCache();
  11054. this._update();
  11055. };
  11056. // Synchronized
  11057. Camera.prototype._isSynchronized = function () {
  11058. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11059. };
  11060. Camera.prototype._isSynchronizedViewMatrix = function () {
  11061. if (!_super.prototype._isSynchronized.call(this))
  11062. return false;
  11063. return this._cache.position.equals(this.position)
  11064. && this._cache.upVector.equals(this.upVector)
  11065. && this.isSynchronizedWithParent();
  11066. };
  11067. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11068. var check = this._cache.mode === this.mode
  11069. && this._cache.minZ === this.minZ
  11070. && this._cache.maxZ === this.maxZ;
  11071. if (!check) {
  11072. return false;
  11073. }
  11074. var engine = this.getEngine();
  11075. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11076. check = this._cache.fov === this.fov
  11077. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11078. }
  11079. else {
  11080. check = this._cache.orthoLeft === this.orthoLeft
  11081. && this._cache.orthoRight === this.orthoRight
  11082. && this._cache.orthoBottom === this.orthoBottom
  11083. && this._cache.orthoTop === this.orthoTop
  11084. && this._cache.renderWidth === engine.getRenderWidth()
  11085. && this._cache.renderHeight === engine.getRenderHeight();
  11086. }
  11087. return check;
  11088. };
  11089. // Controls
  11090. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11091. };
  11092. Camera.prototype.detachControl = function (element) {
  11093. };
  11094. Camera.prototype._update = function () {
  11095. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11096. this._updateRigCameras();
  11097. }
  11098. this._checkInputs();
  11099. };
  11100. Camera.prototype._checkInputs = function () {
  11101. };
  11102. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11103. if (insertAt === void 0) { insertAt = null; }
  11104. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11105. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11106. return 0;
  11107. }
  11108. if (insertAt == null || insertAt < 0) {
  11109. this._postProcesses.push(postProcess);
  11110. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  11111. return this._postProcesses.length - 1;
  11112. }
  11113. var add = 0;
  11114. var i;
  11115. var start;
  11116. if (this._postProcesses[insertAt]) {
  11117. start = this._postProcesses.length - 1;
  11118. for (i = start; i >= insertAt + 1; --i) {
  11119. this._postProcesses[i + 1] = this._postProcesses[i];
  11120. }
  11121. add = 1;
  11122. }
  11123. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11124. if (this._postProcessesTakenIndices[i] < insertAt) {
  11125. continue;
  11126. }
  11127. start = this._postProcessesTakenIndices.length - 1;
  11128. for (var j = start; j >= i; --j) {
  11129. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  11130. }
  11131. this._postProcessesTakenIndices[i] = insertAt;
  11132. break;
  11133. }
  11134. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  11135. this._postProcessesTakenIndices.push(insertAt);
  11136. }
  11137. var result = insertAt + add;
  11138. this._postProcesses[result] = postProcess;
  11139. return result;
  11140. };
  11141. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11142. if (atIndices === void 0) { atIndices = null; }
  11143. var result = [];
  11144. var i;
  11145. var index;
  11146. if (!atIndices) {
  11147. var length = this._postProcesses.length;
  11148. for (i = 0; i < length; i++) {
  11149. if (this._postProcesses[i] !== postProcess) {
  11150. continue;
  11151. }
  11152. delete this._postProcesses[i];
  11153. index = this._postProcessesTakenIndices.indexOf(i);
  11154. this._postProcessesTakenIndices.splice(index, 1);
  11155. }
  11156. }
  11157. else {
  11158. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11159. for (i = 0; i < atIndices.length; i++) {
  11160. var foundPostProcess = this._postProcesses[atIndices[i]];
  11161. if (foundPostProcess !== postProcess) {
  11162. result.push(i);
  11163. continue;
  11164. }
  11165. delete this._postProcesses[atIndices[i]];
  11166. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  11167. this._postProcessesTakenIndices.splice(index, 1);
  11168. }
  11169. }
  11170. return result;
  11171. };
  11172. Camera.prototype.getWorldMatrix = function () {
  11173. if (!this._worldMatrix) {
  11174. this._worldMatrix = BABYLON.Matrix.Identity();
  11175. }
  11176. var viewMatrix = this.getViewMatrix();
  11177. viewMatrix.invertToRef(this._worldMatrix);
  11178. return this._worldMatrix;
  11179. };
  11180. Camera.prototype._getViewMatrix = function () {
  11181. return BABYLON.Matrix.Identity();
  11182. };
  11183. Camera.prototype.getViewMatrix = function (force) {
  11184. this._computedViewMatrix = this._computeViewMatrix(force);
  11185. if (!force && this._isSynchronizedViewMatrix()) {
  11186. return this._computedViewMatrix;
  11187. }
  11188. if (!this.parent || !this.parent.getWorldMatrix) {
  11189. this._globalPosition.copyFrom(this.position);
  11190. }
  11191. else {
  11192. if (!this._worldMatrix) {
  11193. this._worldMatrix = BABYLON.Matrix.Identity();
  11194. }
  11195. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11196. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11197. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11198. this._computedViewMatrix.invert();
  11199. this._markSyncedWithParent();
  11200. }
  11201. this._currentRenderId = this.getScene().getRenderId();
  11202. return this._computedViewMatrix;
  11203. };
  11204. Camera.prototype._computeViewMatrix = function (force) {
  11205. if (!force && this._isSynchronizedViewMatrix()) {
  11206. return this._computedViewMatrix;
  11207. }
  11208. this._computedViewMatrix = this._getViewMatrix();
  11209. this._currentRenderId = this.getScene().getRenderId();
  11210. return this._computedViewMatrix;
  11211. };
  11212. Camera.prototype.getProjectionMatrix = function (force) {
  11213. if (!force && this._isSynchronizedProjectionMatrix()) {
  11214. return this._projectionMatrix;
  11215. }
  11216. var engine = this.getEngine();
  11217. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11218. if (this.minZ <= 0) {
  11219. this.minZ = 0.1;
  11220. }
  11221. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11222. return this._projectionMatrix;
  11223. }
  11224. var halfWidth = engine.getRenderWidth() / 2.0;
  11225. var halfHeight = engine.getRenderHeight() / 2.0;
  11226. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11227. return this._projectionMatrix;
  11228. };
  11229. Camera.prototype.dispose = function () {
  11230. // Animations
  11231. this.getScene().stopAnimation(this);
  11232. // Remove from scene
  11233. this.getScene().removeCamera(this);
  11234. while (this._rigCameras.length > 0) {
  11235. this._rigCameras.pop().dispose();
  11236. }
  11237. // Postprocesses
  11238. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11239. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  11240. }
  11241. _super.prototype.dispose.call(this);
  11242. };
  11243. // ---- Camera rigs section ----
  11244. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11245. while (this._rigCameras.length > 0) {
  11246. this._rigCameras.pop().dispose();
  11247. }
  11248. this.cameraRigMode = mode;
  11249. this._cameraRigParams = {};
  11250. switch (this.cameraRigMode) {
  11251. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11252. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11253. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11254. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11255. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11256. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11257. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11258. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11259. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11260. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11261. break;
  11262. }
  11263. var postProcesses = new Array();
  11264. switch (this.cameraRigMode) {
  11265. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11266. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  11267. this._rigCameras[0].isIntermediate = true;
  11268. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  11269. postProcesses[1].onApply = function (effect) {
  11270. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  11271. };
  11272. break;
  11273. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11274. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11275. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11276. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  11277. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  11278. var secondCamIndex = 1 - firstCamIndex;
  11279. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  11280. this._rigCameras[firstCamIndex].isIntermediate = true;
  11281. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  11282. break;
  11283. case Camera.RIG_MODE_VR:
  11284. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11285. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11286. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11287. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11288. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11289. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11290. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11291. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11292. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11293. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11294. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11295. if (metrics.compensateDistortion) {
  11296. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  11297. }
  11298. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  11299. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11300. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11301. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11302. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11303. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11304. if (metrics.compensateDistortion) {
  11305. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  11306. }
  11307. break;
  11308. }
  11309. this._update();
  11310. };
  11311. Camera.prototype._getVRProjectionMatrix = function () {
  11312. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11313. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11314. return this._projectionMatrix;
  11315. };
  11316. Camera.prototype.setCameraRigParameter = function (name, value) {
  11317. this._cameraRigParams[name] = value;
  11318. //provisionnally:
  11319. if (name === "interaxialDistance") {
  11320. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11321. }
  11322. };
  11323. /**
  11324. * May needs to be overridden by children so sub has required properties to be copied
  11325. */
  11326. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11327. return null;
  11328. };
  11329. /**
  11330. * May needs to be overridden by children
  11331. */
  11332. Camera.prototype._updateRigCameras = function () {
  11333. for (var i = 0; i < this._rigCameras.length; i++) {
  11334. this._rigCameras[i].minZ = this.minZ;
  11335. this._rigCameras[i].maxZ = this.maxZ;
  11336. this._rigCameras[i].fov = this.fov;
  11337. }
  11338. // only update viewport when ANAGLYPH
  11339. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11340. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11341. }
  11342. };
  11343. Camera.prototype._setupInputs = function () {
  11344. };
  11345. Camera.prototype.serialize = function () {
  11346. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11347. // Type
  11348. serializationObject.type = this.getTypeName();
  11349. // Parent
  11350. if (this.parent) {
  11351. serializationObject.parentId = this.parent.id;
  11352. }
  11353. if (this.inputs) {
  11354. this.inputs.serialize(serializationObject);
  11355. }
  11356. // Animations
  11357. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11358. serializationObject.ranges = this.serializeAnimationRanges();
  11359. return serializationObject;
  11360. };
  11361. Camera.prototype.getTypeName = function () {
  11362. return "Camera";
  11363. };
  11364. Camera.prototype.clone = function (name) {
  11365. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11366. };
  11367. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11368. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11369. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11370. switch (type) {
  11371. case "ArcRotateCamera":
  11372. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11373. case "DeviceOrientationCamera":
  11374. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11375. case "FollowCamera":
  11376. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11377. case "ArcFollowCamera":
  11378. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11379. case "GamepadCamera":
  11380. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11381. case "TouchCamera":
  11382. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11383. case "VirtualJoysticksCamera":
  11384. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11385. case "WebVRFreeCamera":
  11386. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11387. case "VRDeviceOrientationFreeCamera":
  11388. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11389. case "AnaglyphArcRotateCamera":
  11390. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11391. case "AnaglyphFreeCamera":
  11392. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11393. case "AnaglyphGamepadCamera":
  11394. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11395. case "AnaglyphUniversalCamera":
  11396. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11397. case "StereoscopicArcRotateCamera":
  11398. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11399. case "StereoscopicFreeCamera":
  11400. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11401. case "StereoscopicGamepadCamera":
  11402. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11403. case "StereoscopicUniversalCamera":
  11404. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11405. case "FreeCamera":
  11406. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11407. default:
  11408. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11409. }
  11410. };
  11411. Camera.Parse = function (parsedCamera, scene) {
  11412. var type = parsedCamera.type;
  11413. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11414. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11415. // Parent
  11416. if (parsedCamera.parentId) {
  11417. camera._waitingParentId = parsedCamera.parentId;
  11418. }
  11419. //If camera has an input manager, let it parse inputs settings
  11420. if (camera.inputs) {
  11421. camera.inputs.parse(parsedCamera);
  11422. camera._setupInputs();
  11423. }
  11424. // Target
  11425. if (parsedCamera.target) {
  11426. if (camera.setTarget) {
  11427. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11428. }
  11429. }
  11430. // Apply 3d rig, when found
  11431. if (parsedCamera.cameraRigMode) {
  11432. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11433. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11434. }
  11435. // Animations
  11436. if (parsedCamera.animations) {
  11437. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11438. var parsedAnimation = parsedCamera.animations[animationIndex];
  11439. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11440. }
  11441. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11442. }
  11443. if (parsedCamera.autoAnimate) {
  11444. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11445. }
  11446. return camera;
  11447. };
  11448. // Statics
  11449. Camera._PERSPECTIVE_CAMERA = 0;
  11450. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11451. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11452. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11453. Camera._RIG_MODE_NONE = 0;
  11454. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11455. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11456. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11457. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11458. Camera._RIG_MODE_VR = 20;
  11459. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11460. __decorate([
  11461. BABYLON.serializeAsVector3()
  11462. ], Camera.prototype, "position", void 0);
  11463. __decorate([
  11464. BABYLON.serializeAsVector3()
  11465. ], Camera.prototype, "upVector", void 0);
  11466. __decorate([
  11467. BABYLON.serialize()
  11468. ], Camera.prototype, "orthoLeft", void 0);
  11469. __decorate([
  11470. BABYLON.serialize()
  11471. ], Camera.prototype, "orthoRight", void 0);
  11472. __decorate([
  11473. BABYLON.serialize()
  11474. ], Camera.prototype, "orthoBottom", void 0);
  11475. __decorate([
  11476. BABYLON.serialize()
  11477. ], Camera.prototype, "orthoTop", void 0);
  11478. __decorate([
  11479. BABYLON.serialize()
  11480. ], Camera.prototype, "fov", void 0);
  11481. __decorate([
  11482. BABYLON.serialize()
  11483. ], Camera.prototype, "minZ", void 0);
  11484. __decorate([
  11485. BABYLON.serialize()
  11486. ], Camera.prototype, "maxZ", void 0);
  11487. __decorate([
  11488. BABYLON.serialize()
  11489. ], Camera.prototype, "inertia", void 0);
  11490. __decorate([
  11491. BABYLON.serialize()
  11492. ], Camera.prototype, "mode", void 0);
  11493. __decorate([
  11494. BABYLON.serialize()
  11495. ], Camera.prototype, "layerMask", void 0);
  11496. __decorate([
  11497. BABYLON.serialize()
  11498. ], Camera.prototype, "fovMode", void 0);
  11499. __decorate([
  11500. BABYLON.serialize()
  11501. ], Camera.prototype, "cameraRigMode", void 0);
  11502. __decorate([
  11503. BABYLON.serialize()
  11504. ], Camera.prototype, "interaxialDistance", void 0);
  11505. __decorate([
  11506. BABYLON.serialize()
  11507. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11508. return Camera;
  11509. })(BABYLON.Node);
  11510. BABYLON.Camera = Camera;
  11511. })(BABYLON || (BABYLON = {}));
  11512. var BABYLON;
  11513. (function (BABYLON) {
  11514. BABYLON.CameraInputTypes = {};
  11515. var CameraInputsManager = (function () {
  11516. function CameraInputsManager(camera) {
  11517. this.attached = {};
  11518. this.camera = camera;
  11519. this.checkInputs = function () { };
  11520. }
  11521. CameraInputsManager.prototype.add = function (input) {
  11522. var type = input.getSimpleName();
  11523. if (this.attached[type]) {
  11524. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11525. return;
  11526. }
  11527. this.attached[type] = input;
  11528. input.camera = this.camera;
  11529. //for checkInputs, we are dynamically creating a function
  11530. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11531. if (input.checkInputs) {
  11532. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11533. }
  11534. if (this.attachedElement) {
  11535. input.attachControl(this.attachedElement);
  11536. }
  11537. };
  11538. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11539. for (var cam in this.attached) {
  11540. var input = this.attached[cam];
  11541. if (input === inputToRemove) {
  11542. input.detachControl(this.attachedElement);
  11543. delete this.attached[cam];
  11544. this.rebuildInputCheck();
  11545. }
  11546. }
  11547. };
  11548. CameraInputsManager.prototype.removeByType = function (inputType) {
  11549. for (var cam in this.attached) {
  11550. var input = this.attached[cam];
  11551. if (input.getTypeName() === inputType) {
  11552. input.detachControl(this.attachedElement);
  11553. delete this.attached[cam];
  11554. this.rebuildInputCheck();
  11555. }
  11556. }
  11557. };
  11558. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11559. var current = this.checkInputs;
  11560. return function () {
  11561. current();
  11562. fn();
  11563. };
  11564. };
  11565. CameraInputsManager.prototype.attachInput = function (input) {
  11566. input.attachControl(this.attachedElement, this.noPreventDefault);
  11567. };
  11568. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11569. if (this.attachedElement) {
  11570. return;
  11571. }
  11572. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11573. this.attachedElement = element;
  11574. this.noPreventDefault = noPreventDefault;
  11575. for (var cam in this.attached) {
  11576. var input = this.attached[cam];
  11577. this.attached[cam].attachControl(element, noPreventDefault);
  11578. }
  11579. };
  11580. CameraInputsManager.prototype.detachElement = function (element) {
  11581. if (this.attachedElement !== element) {
  11582. return;
  11583. }
  11584. for (var cam in this.attached) {
  11585. var input = this.attached[cam];
  11586. this.attached[cam].detachControl(element);
  11587. }
  11588. this.attachedElement = null;
  11589. };
  11590. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11591. this.checkInputs = function () { };
  11592. for (var cam in this.attached) {
  11593. var input = this.attached[cam];
  11594. if (input.checkInputs) {
  11595. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11596. }
  11597. }
  11598. };
  11599. CameraInputsManager.prototype.clear = function () {
  11600. if (this.attachedElement) {
  11601. this.detachElement(this.attachedElement);
  11602. }
  11603. this.attached = {};
  11604. this.attachedElement = null;
  11605. this.checkInputs = function () { };
  11606. };
  11607. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11608. var inputs = {};
  11609. for (var cam in this.attached) {
  11610. var input = this.attached[cam];
  11611. var res = BABYLON.SerializationHelper.Serialize(input);
  11612. inputs[input.getTypeName()] = res;
  11613. }
  11614. serializedCamera.inputsmgr = inputs;
  11615. };
  11616. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11617. var parsedInputs = parsedCamera.inputsmgr;
  11618. if (parsedInputs) {
  11619. this.clear();
  11620. for (var n in parsedInputs) {
  11621. var construct = BABYLON.CameraInputTypes[n];
  11622. if (construct) {
  11623. var parsedinput = parsedInputs[n];
  11624. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11625. this.add(input);
  11626. }
  11627. }
  11628. }
  11629. else {
  11630. //2016-03-08 this part is for managing backward compatibility
  11631. for (var n in this.attached) {
  11632. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11633. if (construct) {
  11634. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11635. this.remove(this.attached[n]);
  11636. this.add(input);
  11637. }
  11638. }
  11639. }
  11640. };
  11641. return CameraInputsManager;
  11642. })();
  11643. BABYLON.CameraInputsManager = CameraInputsManager;
  11644. })(BABYLON || (BABYLON = {}));
  11645. var BABYLON;
  11646. (function (BABYLON) {
  11647. var FreeCameraMouseInput = (function () {
  11648. function FreeCameraMouseInput(touchEnabled) {
  11649. if (touchEnabled === void 0) { touchEnabled = true; }
  11650. this.touchEnabled = touchEnabled;
  11651. this.angularSensibility = 2000.0;
  11652. }
  11653. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11654. var _this = this;
  11655. if (!this._pointerInput) {
  11656. var camera = this.camera;
  11657. var engine = this.camera.getEngine();
  11658. this._pointerInput = function (p, s) {
  11659. var evt = p.event;
  11660. if (!_this.touchEnabled && evt.pointerType === "touch") {
  11661. return;
  11662. }
  11663. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11664. try {
  11665. evt.srcElement.setPointerCapture(evt.pointerId);
  11666. }
  11667. catch (e) {
  11668. }
  11669. _this.previousPosition = {
  11670. x: evt.clientX,
  11671. y: evt.clientY
  11672. };
  11673. if (!noPreventDefault) {
  11674. evt.preventDefault();
  11675. }
  11676. }
  11677. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11678. try {
  11679. evt.srcElement.releasePointerCapture(evt.pointerId);
  11680. }
  11681. catch (e) {
  11682. }
  11683. _this.previousPosition = null;
  11684. if (!noPreventDefault) {
  11685. evt.preventDefault();
  11686. }
  11687. }
  11688. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11689. if (!_this.previousPosition && !engine.isPointerLock) {
  11690. return;
  11691. }
  11692. var offsetX;
  11693. var offsetY;
  11694. if (!engine.isPointerLock) {
  11695. offsetX = evt.clientX - _this.previousPosition.x;
  11696. offsetY = evt.clientY - _this.previousPosition.y;
  11697. }
  11698. else {
  11699. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11700. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11701. }
  11702. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11703. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11704. _this.previousPosition = {
  11705. x: evt.clientX,
  11706. y: evt.clientY
  11707. };
  11708. if (!noPreventDefault) {
  11709. evt.preventDefault();
  11710. }
  11711. }
  11712. };
  11713. }
  11714. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11715. };
  11716. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11717. if (this._observer && element) {
  11718. this.camera.getScene().onPointerObservable.remove(this._observer);
  11719. this._observer = null;
  11720. this.previousPosition = null;
  11721. }
  11722. };
  11723. FreeCameraMouseInput.prototype.getTypeName = function () {
  11724. return "FreeCameraMouseInput";
  11725. };
  11726. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11727. return "mouse";
  11728. };
  11729. __decorate([
  11730. BABYLON.serialize()
  11731. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11732. return FreeCameraMouseInput;
  11733. })();
  11734. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11735. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11736. })(BABYLON || (BABYLON = {}));
  11737. var BABYLON;
  11738. (function (BABYLON) {
  11739. var FreeCameraKeyboardMoveInput = (function () {
  11740. function FreeCameraKeyboardMoveInput() {
  11741. this._keys = [];
  11742. this.keysUp = [38];
  11743. this.keysDown = [40];
  11744. this.keysLeft = [37];
  11745. this.keysRight = [39];
  11746. }
  11747. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11748. var _this = this;
  11749. if (!this._onKeyDown) {
  11750. this._onKeyDown = function (evt) {
  11751. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11752. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11753. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11754. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11755. var index = _this._keys.indexOf(evt.keyCode);
  11756. if (index === -1) {
  11757. _this._keys.push(evt.keyCode);
  11758. }
  11759. if (!noPreventDefault) {
  11760. evt.preventDefault();
  11761. }
  11762. }
  11763. };
  11764. this._onKeyUp = function (evt) {
  11765. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11766. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11767. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11768. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11769. var index = _this._keys.indexOf(evt.keyCode);
  11770. if (index >= 0) {
  11771. _this._keys.splice(index, 1);
  11772. }
  11773. if (!noPreventDefault) {
  11774. evt.preventDefault();
  11775. }
  11776. }
  11777. };
  11778. BABYLON.Tools.RegisterTopRootEvents([
  11779. { name: "keydown", handler: this._onKeyDown },
  11780. { name: "keyup", handler: this._onKeyUp },
  11781. { name: "blur", handler: this._onLostFocus }
  11782. ]);
  11783. }
  11784. };
  11785. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11786. if (this._onKeyDown) {
  11787. BABYLON.Tools.UnregisterTopRootEvents([
  11788. { name: "keydown", handler: this._onKeyDown },
  11789. { name: "keyup", handler: this._onKeyUp },
  11790. { name: "blur", handler: this._onLostFocus }
  11791. ]);
  11792. this._keys = [];
  11793. this._onKeyDown = null;
  11794. this._onKeyUp = null;
  11795. }
  11796. };
  11797. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11798. if (this._onKeyDown) {
  11799. var camera = this.camera;
  11800. // Keyboard
  11801. for (var index = 0; index < this._keys.length; index++) {
  11802. var keyCode = this._keys[index];
  11803. var speed = camera._computeLocalCameraSpeed();
  11804. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11805. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11806. }
  11807. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11808. camera._localDirection.copyFromFloats(0, 0, speed);
  11809. }
  11810. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11811. camera._localDirection.copyFromFloats(speed, 0, 0);
  11812. }
  11813. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11814. camera._localDirection.copyFromFloats(0, 0, -speed);
  11815. }
  11816. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11817. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11818. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11819. }
  11820. }
  11821. };
  11822. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11823. return "FreeCameraKeyboardMoveInput";
  11824. };
  11825. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11826. this._keys = [];
  11827. };
  11828. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11829. return "keyboard";
  11830. };
  11831. __decorate([
  11832. BABYLON.serialize()
  11833. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11834. __decorate([
  11835. BABYLON.serialize()
  11836. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11837. __decorate([
  11838. BABYLON.serialize()
  11839. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11840. __decorate([
  11841. BABYLON.serialize()
  11842. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11843. return FreeCameraKeyboardMoveInput;
  11844. })();
  11845. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11846. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11847. })(BABYLON || (BABYLON = {}));
  11848. var BABYLON;
  11849. (function (BABYLON) {
  11850. var FreeCameraTouchInput = (function () {
  11851. function FreeCameraTouchInput() {
  11852. this._offsetX = null;
  11853. this._offsetY = null;
  11854. this._pointerCount = 0;
  11855. this._pointerPressed = [];
  11856. this.touchAngularSensibility = 200000.0;
  11857. this.touchMoveSensibility = 250.0;
  11858. }
  11859. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11860. var _this = this;
  11861. var previousPosition;
  11862. if (this._pointerInput === undefined) {
  11863. this._onLostFocus = function (evt) {
  11864. _this._offsetX = null;
  11865. _this._offsetY = null;
  11866. };
  11867. this._pointerInput = function (p, s) {
  11868. var evt = p.event;
  11869. if (evt.pointerType === "mouse") {
  11870. return;
  11871. }
  11872. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11873. if (!noPreventDefault) {
  11874. evt.preventDefault();
  11875. }
  11876. _this._pointerPressed.push(evt.pointerId);
  11877. if (_this._pointerPressed.length !== 1) {
  11878. return;
  11879. }
  11880. previousPosition = {
  11881. x: evt.clientX,
  11882. y: evt.clientY
  11883. };
  11884. }
  11885. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11886. if (!noPreventDefault) {
  11887. evt.preventDefault();
  11888. }
  11889. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11890. if (index === -1) {
  11891. return;
  11892. }
  11893. _this._pointerPressed.splice(index, 1);
  11894. if (index != 0) {
  11895. return;
  11896. }
  11897. previousPosition = null;
  11898. _this._offsetX = null;
  11899. _this._offsetY = null;
  11900. }
  11901. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11902. if (!noPreventDefault) {
  11903. evt.preventDefault();
  11904. }
  11905. if (!previousPosition) {
  11906. return;
  11907. }
  11908. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11909. if (index != 0) {
  11910. return;
  11911. }
  11912. _this._offsetX = evt.clientX - previousPosition.x;
  11913. _this._offsetY = -(evt.clientY - previousPosition.y);
  11914. }
  11915. };
  11916. }
  11917. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11918. element.addEventListener("blur", this._onLostFocus);
  11919. };
  11920. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11921. if (this._pointerInput && element) {
  11922. this.camera.getScene().onPointerObservable.remove(this._observer);
  11923. this._observer = null;
  11924. element.removeEventListener("blur", this._onLostFocus);
  11925. this._onLostFocus = null;
  11926. this._pointerPressed = [];
  11927. this._offsetX = null;
  11928. this._offsetY = null;
  11929. this._pointerCount = 0;
  11930. }
  11931. };
  11932. FreeCameraTouchInput.prototype.checkInputs = function () {
  11933. if (this._offsetX) {
  11934. var camera = this.camera;
  11935. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11936. if (this._pointerPressed.length > 1) {
  11937. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11938. }
  11939. else {
  11940. var speed = camera._computeLocalCameraSpeed();
  11941. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11942. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11943. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11944. }
  11945. }
  11946. };
  11947. FreeCameraTouchInput.prototype.getTypeName = function () {
  11948. return "FreeCameraTouchInput";
  11949. };
  11950. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11951. return "touch";
  11952. };
  11953. __decorate([
  11954. BABYLON.serialize()
  11955. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11956. __decorate([
  11957. BABYLON.serialize()
  11958. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11959. return FreeCameraTouchInput;
  11960. })();
  11961. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11962. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11963. })(BABYLON || (BABYLON = {}));
  11964. var BABYLON;
  11965. (function (BABYLON) {
  11966. var FreeCameraDeviceOrientationInput = (function () {
  11967. function FreeCameraDeviceOrientationInput() {
  11968. this._offsetX = null;
  11969. this._offsetY = null;
  11970. this._orientationGamma = 0;
  11971. this._orientationBeta = 0;
  11972. this._initialOrientationGamma = 0;
  11973. this._initialOrientationBeta = 0;
  11974. this.angularSensibility = 10000.0;
  11975. this.moveSensibility = 50.0;
  11976. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11977. this._orientationChanged = this.orientationChanged.bind(this);
  11978. }
  11979. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11980. window.addEventListener("resize", this._resetOrientationGamma, false);
  11981. window.addEventListener("deviceorientation", this._orientationChanged);
  11982. };
  11983. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11984. this._initialOrientationGamma = null;
  11985. };
  11986. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11987. if (!this._initialOrientationGamma) {
  11988. this._initialOrientationGamma = evt.gamma;
  11989. this._initialOrientationBeta = evt.beta;
  11990. }
  11991. this._orientationGamma = evt.gamma;
  11992. this._orientationBeta = evt.beta;
  11993. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11994. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11995. };
  11996. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11997. window.removeEventListener("resize", this._resetOrientationGamma);
  11998. window.removeEventListener("deviceorientation", this._orientationChanged);
  11999. this._orientationGamma = 0;
  12000. this._orientationBeta = 0;
  12001. this._initialOrientationGamma = 0;
  12002. this._initialOrientationBeta = 0;
  12003. this._offsetX = null;
  12004. this._offsetY = null;
  12005. };
  12006. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12007. if (!this._offsetX) {
  12008. return;
  12009. }
  12010. var camera = this.camera;
  12011. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  12012. var speed = camera._computeLocalCameraSpeed();
  12013. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  12014. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12015. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12016. };
  12017. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12018. return "FreeCameraDeviceOrientationInput";
  12019. };
  12020. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12021. return "deviceOrientation";
  12022. };
  12023. __decorate([
  12024. BABYLON.serialize()
  12025. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  12026. __decorate([
  12027. BABYLON.serialize()
  12028. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  12029. return FreeCameraDeviceOrientationInput;
  12030. })();
  12031. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12032. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12033. })(BABYLON || (BABYLON = {}));
  12034. var BABYLON;
  12035. (function (BABYLON) {
  12036. var FreeCameraVRDeviceOrientationInput = (function () {
  12037. function FreeCameraVRDeviceOrientationInput() {
  12038. this.alphaCorrection = 1;
  12039. this.betaCorrection = 1;
  12040. this.gammaCorrection = 1;
  12041. this._alpha = 0;
  12042. this._beta = 0;
  12043. this._gamma = 0;
  12044. this._dirty = false;
  12045. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12046. }
  12047. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12048. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12049. };
  12050. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12051. var camera = this.camera;
  12052. this._alpha = +evt.alpha | 0;
  12053. this._beta = +evt.beta | 0;
  12054. this._gamma = +evt.gamma | 0;
  12055. this._dirty = true;
  12056. };
  12057. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12058. if (this._dirty) {
  12059. this._dirty = false;
  12060. var rotationX = this._gamma;
  12061. if (rotationX < 0) {
  12062. rotationX = 90 + rotationX;
  12063. }
  12064. else {
  12065. // Incline it in the correct angle.
  12066. rotationX = 270 - rotationX;
  12067. }
  12068. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12069. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12070. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12071. }
  12072. };
  12073. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12074. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12075. };
  12076. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12077. return "FreeCameraVRDeviceOrientationInput";
  12078. };
  12079. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12080. return "VRDeviceOrientation";
  12081. };
  12082. return FreeCameraVRDeviceOrientationInput;
  12083. })();
  12084. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12085. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12086. })(BABYLON || (BABYLON = {}));
  12087. var BABYLON;
  12088. (function (BABYLON) {
  12089. var FreeCameraGamepadInput = (function () {
  12090. function FreeCameraGamepadInput() {
  12091. this.gamepadAngularSensibility = 200;
  12092. this.gamepadMoveSensibility = 40;
  12093. }
  12094. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12095. var _this = this;
  12096. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12097. };
  12098. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12099. if (this._gamepads) {
  12100. this._gamepads.dispose();
  12101. }
  12102. this.gamepad = null;
  12103. };
  12104. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12105. if (this.gamepad) {
  12106. var camera = this.camera;
  12107. var LSValues = this.gamepad.leftStick;
  12108. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12109. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12110. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12111. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12112. var RSValues = this.gamepad.rightStick;
  12113. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12114. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12115. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12116. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12117. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12118. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12119. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12120. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12121. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12122. }
  12123. };
  12124. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12125. // Only the first gamepad can control the camera
  12126. if (gamepad.index === 0) {
  12127. this.gamepad = gamepad;
  12128. }
  12129. };
  12130. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12131. return "FreeCameraGamepadInput";
  12132. };
  12133. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12134. return "gamepad";
  12135. };
  12136. __decorate([
  12137. BABYLON.serialize()
  12138. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12139. __decorate([
  12140. BABYLON.serialize()
  12141. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12142. return FreeCameraGamepadInput;
  12143. })();
  12144. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12145. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12146. })(BABYLON || (BABYLON = {}));
  12147. var BABYLON;
  12148. (function (BABYLON) {
  12149. var FreeCameraVirtualJoystickInput = (function () {
  12150. function FreeCameraVirtualJoystickInput() {
  12151. }
  12152. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  12153. return this._leftjoystick;
  12154. };
  12155. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  12156. return this._rightjoystick;
  12157. };
  12158. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  12159. if (this._leftjoystick) {
  12160. var camera = this.camera;
  12161. var speed = camera._computeLocalCameraSpeed() * 50;
  12162. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12163. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  12164. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12165. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  12166. if (!this._leftjoystick.pressed) {
  12167. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  12168. }
  12169. if (!this._rightjoystick.pressed) {
  12170. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  12171. }
  12172. }
  12173. };
  12174. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  12175. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  12176. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  12177. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  12178. this._leftjoystick.setJoystickSensibility(0.15);
  12179. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  12180. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  12181. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  12182. this._rightjoystick.reverseUpDown = true;
  12183. this._rightjoystick.setJoystickSensibility(0.05);
  12184. this._rightjoystick.setJoystickColor("yellow");
  12185. };
  12186. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  12187. this._leftjoystick.releaseCanvas();
  12188. this._rightjoystick.releaseCanvas();
  12189. };
  12190. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  12191. return "FreeCameraVirtualJoystickInput";
  12192. };
  12193. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  12194. return "virtualJoystick";
  12195. };
  12196. return FreeCameraVirtualJoystickInput;
  12197. })();
  12198. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  12199. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  12200. })(BABYLON || (BABYLON = {}));
  12201. var BABYLON;
  12202. (function (BABYLON) {
  12203. var ArcRotateCameraKeyboardMoveInput = (function () {
  12204. function ArcRotateCameraKeyboardMoveInput() {
  12205. this._keys = [];
  12206. this.keysUp = [38];
  12207. this.keysDown = [40];
  12208. this.keysLeft = [37];
  12209. this.keysRight = [39];
  12210. }
  12211. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12212. var _this = this;
  12213. this._onKeyDown = function (evt) {
  12214. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12215. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12216. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12217. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12218. var index = _this._keys.indexOf(evt.keyCode);
  12219. if (index === -1) {
  12220. _this._keys.push(evt.keyCode);
  12221. }
  12222. if (evt.preventDefault) {
  12223. if (!noPreventDefault) {
  12224. evt.preventDefault();
  12225. }
  12226. }
  12227. }
  12228. };
  12229. this._onKeyUp = function (evt) {
  12230. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12231. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12232. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12233. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12234. var index = _this._keys.indexOf(evt.keyCode);
  12235. if (index >= 0) {
  12236. _this._keys.splice(index, 1);
  12237. }
  12238. if (evt.preventDefault) {
  12239. if (!noPreventDefault) {
  12240. evt.preventDefault();
  12241. }
  12242. }
  12243. }
  12244. };
  12245. this._onLostFocus = function () {
  12246. _this._keys = [];
  12247. };
  12248. BABYLON.Tools.RegisterTopRootEvents([
  12249. { name: "keydown", handler: this._onKeyDown },
  12250. { name: "keyup", handler: this._onKeyUp },
  12251. { name: "blur", handler: this._onLostFocus }
  12252. ]);
  12253. };
  12254. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12255. BABYLON.Tools.UnregisterTopRootEvents([
  12256. { name: "keydown", handler: this._onKeyDown },
  12257. { name: "keyup", handler: this._onKeyUp },
  12258. { name: "blur", handler: this._onLostFocus }
  12259. ]);
  12260. this._keys = [];
  12261. this._onKeyDown = null;
  12262. this._onKeyUp = null;
  12263. this._onLostFocus = null;
  12264. };
  12265. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12266. if (this._onKeyDown) {
  12267. var camera = this.camera;
  12268. for (var index = 0; index < this._keys.length; index++) {
  12269. var keyCode = this._keys[index];
  12270. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12271. camera.inertialAlphaOffset -= 0.01;
  12272. }
  12273. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12274. camera.inertialBetaOffset -= 0.01;
  12275. }
  12276. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12277. camera.inertialAlphaOffset += 0.01;
  12278. }
  12279. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12280. camera.inertialBetaOffset += 0.01;
  12281. }
  12282. }
  12283. }
  12284. };
  12285. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12286. return "ArcRotateCameraKeyboardMoveInput";
  12287. };
  12288. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12289. return "keyboard";
  12290. };
  12291. __decorate([
  12292. BABYLON.serialize()
  12293. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12294. __decorate([
  12295. BABYLON.serialize()
  12296. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12297. __decorate([
  12298. BABYLON.serialize()
  12299. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12300. __decorate([
  12301. BABYLON.serialize()
  12302. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12303. return ArcRotateCameraKeyboardMoveInput;
  12304. })();
  12305. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12306. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12307. })(BABYLON || (BABYLON = {}));
  12308. var BABYLON;
  12309. (function (BABYLON) {
  12310. var ArcRotateCameraMouseWheelInput = (function () {
  12311. function ArcRotateCameraMouseWheelInput() {
  12312. this.wheelPrecision = 3.0;
  12313. }
  12314. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12315. var _this = this;
  12316. this._wheel = function (p, s) {
  12317. //sanity check - this should be a PointerWheel event.
  12318. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12319. return;
  12320. var event = p.event;
  12321. var delta = 0;
  12322. if (event.wheelDelta) {
  12323. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12324. }
  12325. else if (event.detail) {
  12326. delta = -event.detail / _this.wheelPrecision;
  12327. }
  12328. if (delta)
  12329. _this.camera.inertialRadiusOffset += delta;
  12330. if (event.preventDefault) {
  12331. if (!noPreventDefault) {
  12332. event.preventDefault();
  12333. }
  12334. }
  12335. };
  12336. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12337. };
  12338. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12339. if (this._observer && element) {
  12340. this.camera.getScene().onPointerObservable.remove(this._observer);
  12341. this._observer = null;
  12342. this._wheel = null;
  12343. }
  12344. };
  12345. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12346. return "ArcRotateCameraMouseWheelInput";
  12347. };
  12348. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12349. return "mousewheel";
  12350. };
  12351. __decorate([
  12352. BABYLON.serialize()
  12353. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12354. return ArcRotateCameraMouseWheelInput;
  12355. })();
  12356. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12357. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12358. })(BABYLON || (BABYLON = {}));
  12359. var BABYLON;
  12360. (function (BABYLON) {
  12361. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12362. var ArcRotateCameraPointersInput = (function () {
  12363. function ArcRotateCameraPointersInput() {
  12364. this.angularSensibilityX = 1000.0;
  12365. this.angularSensibilityY = 1000.0;
  12366. this.pinchPrecision = 6.0;
  12367. this.panningSensibility = 50.0;
  12368. this._isRightClick = false;
  12369. this._isCtrlPushed = false;
  12370. this.pinchInwards = true;
  12371. }
  12372. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12373. var _this = this;
  12374. var engine = this.camera.getEngine();
  12375. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12376. var pointA, pointB;
  12377. var previousPinchDistance = 0;
  12378. this._pointerInput = function (p, s) {
  12379. var evt = p.event;
  12380. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12381. try {
  12382. evt.srcElement.setPointerCapture(evt.pointerId);
  12383. }
  12384. catch (e) {
  12385. }
  12386. // Manage panning with right click
  12387. _this._isRightClick = evt.button === 2;
  12388. // manage pointers
  12389. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  12390. if (pointA === undefined) {
  12391. pointA = cacheSoloPointer;
  12392. }
  12393. else if (pointB === undefined) {
  12394. pointB = cacheSoloPointer;
  12395. }
  12396. if (!noPreventDefault) {
  12397. evt.preventDefault();
  12398. }
  12399. }
  12400. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12401. try {
  12402. evt.srcElement.releasePointerCapture(evt.pointerId);
  12403. }
  12404. catch (e) {
  12405. }
  12406. cacheSoloPointer = null;
  12407. previousPinchDistance = 0;
  12408. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12409. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12410. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12411. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12412. pointA = pointB = undefined;
  12413. if (!noPreventDefault) {
  12414. evt.preventDefault();
  12415. }
  12416. }
  12417. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12418. if (!noPreventDefault) {
  12419. evt.preventDefault();
  12420. }
  12421. // One button down
  12422. if (pointA && pointB === undefined) {
  12423. if (_this.panningSensibility !== 0 &&
  12424. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  12425. (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12426. _this.camera
  12427. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12428. _this.camera
  12429. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12430. }
  12431. else {
  12432. var offsetX = evt.clientX - cacheSoloPointer.x;
  12433. var offsetY = evt.clientY - cacheSoloPointer.y;
  12434. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12435. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12436. }
  12437. cacheSoloPointer.x = evt.clientX;
  12438. cacheSoloPointer.y = evt.clientY;
  12439. }
  12440. else if (pointA && pointB) {
  12441. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12442. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  12443. ed.x = evt.clientX;
  12444. ed.y = evt.clientY;
  12445. var direction = _this.pinchInwards ? 1 : -1;
  12446. var distX = pointA.x - pointB.x;
  12447. var distY = pointA.y - pointB.y;
  12448. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12449. if (previousPinchDistance === 0) {
  12450. previousPinchDistance = pinchSquaredDistance;
  12451. return;
  12452. }
  12453. if (pinchSquaredDistance !== previousPinchDistance) {
  12454. _this.camera
  12455. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  12456. (_this.pinchPrecision *
  12457. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  12458. direction);
  12459. previousPinchDistance = pinchSquaredDistance;
  12460. }
  12461. }
  12462. }
  12463. };
  12464. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12465. this._onContextMenu = function (evt) {
  12466. evt.preventDefault();
  12467. };
  12468. if (!this.camera._useCtrlForPanning) {
  12469. element.addEventListener("contextmenu", this._onContextMenu, false);
  12470. }
  12471. this._onLostFocus = function () {
  12472. //this._keys = [];
  12473. pointA = pointB = undefined;
  12474. previousPinchDistance = 0;
  12475. cacheSoloPointer = null;
  12476. };
  12477. this._onKeyDown = function (evt) {
  12478. _this._isCtrlPushed = evt.ctrlKey;
  12479. };
  12480. this._onKeyUp = function (evt) {
  12481. _this._isCtrlPushed = evt.ctrlKey;
  12482. };
  12483. this._onMouseMove = function (evt) {
  12484. if (!engine.isPointerLock) {
  12485. return;
  12486. }
  12487. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12488. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12489. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12490. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12491. if (!noPreventDefault) {
  12492. evt.preventDefault();
  12493. }
  12494. };
  12495. this._onGestureStart = function (e) {
  12496. if (window.MSGesture === undefined) {
  12497. return;
  12498. }
  12499. if (!_this._MSGestureHandler) {
  12500. _this._MSGestureHandler = new MSGesture();
  12501. _this._MSGestureHandler.target = element;
  12502. }
  12503. _this._MSGestureHandler.addPointer(e.pointerId);
  12504. };
  12505. this._onGesture = function (e) {
  12506. _this.camera.radius *= e.scale;
  12507. if (e.preventDefault) {
  12508. if (!noPreventDefault) {
  12509. e.stopPropagation();
  12510. e.preventDefault();
  12511. }
  12512. }
  12513. };
  12514. element.addEventListener("mousemove", this._onMouseMove, false);
  12515. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12516. element.addEventListener("MSGestureChange", this._onGesture, false);
  12517. BABYLON.Tools.RegisterTopRootEvents([
  12518. { name: "keydown", handler: this._onKeyDown },
  12519. { name: "keyup", handler: this._onKeyUp },
  12520. { name: "blur", handler: this._onLostFocus }
  12521. ]);
  12522. };
  12523. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12524. if (element && this._observer) {
  12525. this.camera.getScene().onPointerObservable.remove(this._observer);
  12526. this._observer = null;
  12527. element.removeEventListener("contextmenu", this._onContextMenu);
  12528. element.removeEventListener("mousemove", this._onMouseMove);
  12529. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12530. element.removeEventListener("MSGestureChange", this._onGesture);
  12531. this._isRightClick = false;
  12532. this._isCtrlPushed = false;
  12533. this.pinchInwards = true;
  12534. this._onKeyDown = null;
  12535. this._onKeyUp = null;
  12536. this._onMouseMove = null;
  12537. this._onGestureStart = null;
  12538. this._onGesture = null;
  12539. this._MSGestureHandler = null;
  12540. this._onLostFocus = null;
  12541. this._onContextMenu = null;
  12542. }
  12543. BABYLON.Tools.UnregisterTopRootEvents([
  12544. { name: "keydown", handler: this._onKeyDown },
  12545. { name: "keyup", handler: this._onKeyUp },
  12546. { name: "blur", handler: this._onLostFocus }
  12547. ]);
  12548. };
  12549. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12550. return "ArcRotateCameraPointersInput";
  12551. };
  12552. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12553. return "pointers";
  12554. };
  12555. __decorate([
  12556. BABYLON.serialize()
  12557. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12558. __decorate([
  12559. BABYLON.serialize()
  12560. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12561. __decorate([
  12562. BABYLON.serialize()
  12563. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12564. __decorate([
  12565. BABYLON.serialize()
  12566. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12567. return ArcRotateCameraPointersInput;
  12568. })();
  12569. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12570. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12571. })(BABYLON || (BABYLON = {}));
  12572. var BABYLON;
  12573. (function (BABYLON) {
  12574. var ArcRotateCameraGamepadInput = (function () {
  12575. function ArcRotateCameraGamepadInput() {
  12576. this.gamepadRotationSensibility = 80;
  12577. this.gamepadMoveSensibility = 40;
  12578. }
  12579. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12580. var _this = this;
  12581. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12582. };
  12583. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12584. if (this._gamepads) {
  12585. this._gamepads.dispose();
  12586. }
  12587. this.gamepad = null;
  12588. };
  12589. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12590. if (this.gamepad) {
  12591. var camera = this.camera;
  12592. var RSValues = this.gamepad.rightStick;
  12593. if (RSValues.x != 0) {
  12594. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12595. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12596. camera.inertialAlphaOffset += normalizedRX;
  12597. }
  12598. }
  12599. if (RSValues.y != 0) {
  12600. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12601. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12602. camera.inertialBetaOffset += normalizedRY;
  12603. }
  12604. }
  12605. var LSValues = this.gamepad.leftStick;
  12606. if (LSValues.y != 0) {
  12607. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12608. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12609. this.camera.inertialRadiusOffset -= normalizedLY;
  12610. }
  12611. }
  12612. }
  12613. };
  12614. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12615. // Only the first gamepad can control the camera
  12616. if (gamepad.index === 0) {
  12617. this.gamepad = gamepad;
  12618. }
  12619. };
  12620. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12621. return "ArcRotateCameraGamepadInput";
  12622. };
  12623. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12624. return "gamepad";
  12625. };
  12626. __decorate([
  12627. BABYLON.serialize()
  12628. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12629. __decorate([
  12630. BABYLON.serialize()
  12631. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12632. return ArcRotateCameraGamepadInput;
  12633. })();
  12634. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12635. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12636. })(BABYLON || (BABYLON = {}));
  12637. var BABYLON;
  12638. (function (BABYLON) {
  12639. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12640. function ArcRotateCameraVRDeviceOrientationInput() {
  12641. this.alphaCorrection = 1;
  12642. this.betaCorrection = 1;
  12643. this.gammaCorrection = 1;
  12644. this._alpha = 0;
  12645. this._beta = 0;
  12646. this._gamma = 0;
  12647. this._dirty = false;
  12648. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12649. }
  12650. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12651. this.camera.attachControl(element, noPreventDefault);
  12652. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12653. };
  12654. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12655. var camera = this.camera;
  12656. this._alpha = +evt.alpha | 0;
  12657. this._beta = +evt.beta | 0;
  12658. this._gamma = +evt.gamma | 0;
  12659. this._dirty = true;
  12660. };
  12661. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12662. if (this._dirty) {
  12663. this._dirty = false;
  12664. if (this._gamma < 0) {
  12665. this._gamma = 180 + this._gamma;
  12666. }
  12667. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12668. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12669. }
  12670. };
  12671. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12672. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12673. };
  12674. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12675. return "ArcRotateCameraVRDeviceOrientationInput";
  12676. };
  12677. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12678. return "VRDeviceOrientation";
  12679. };
  12680. return ArcRotateCameraVRDeviceOrientationInput;
  12681. })();
  12682. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12683. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12684. })(BABYLON || (BABYLON = {}));
  12685. var BABYLON;
  12686. (function (BABYLON) {
  12687. var TargetCamera = (function (_super) {
  12688. __extends(TargetCamera, _super);
  12689. function TargetCamera(name, position, scene) {
  12690. _super.call(this, name, position, scene);
  12691. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12692. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12693. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12694. this.speed = 2.0;
  12695. this.noRotationConstraint = false;
  12696. this.lockedTarget = null;
  12697. this._currentTarget = BABYLON.Vector3.Zero();
  12698. this._viewMatrix = BABYLON.Matrix.Zero();
  12699. this._camMatrix = BABYLON.Matrix.Zero();
  12700. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12701. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12702. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12703. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12704. this._lookAtTemp = BABYLON.Matrix.Zero();
  12705. this._tempMatrix = BABYLON.Matrix.Zero();
  12706. }
  12707. TargetCamera.prototype.getFrontPosition = function (distance) {
  12708. var direction = this.getTarget().subtract(this.position);
  12709. direction.normalize();
  12710. direction.scaleInPlace(distance);
  12711. return this.globalPosition.add(direction);
  12712. };
  12713. TargetCamera.prototype._getLockedTargetPosition = function () {
  12714. if (!this.lockedTarget) {
  12715. return null;
  12716. }
  12717. return this.lockedTarget.position || this.lockedTarget;
  12718. };
  12719. // Cache
  12720. TargetCamera.prototype._initCache = function () {
  12721. _super.prototype._initCache.call(this);
  12722. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12723. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12724. };
  12725. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12726. if (!ignoreParentClass) {
  12727. _super.prototype._updateCache.call(this);
  12728. }
  12729. var lockedTargetPosition = this._getLockedTargetPosition();
  12730. if (!lockedTargetPosition) {
  12731. this._cache.lockedTarget = null;
  12732. }
  12733. else {
  12734. if (!this._cache.lockedTarget) {
  12735. this._cache.lockedTarget = lockedTargetPosition.clone();
  12736. }
  12737. else {
  12738. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12739. }
  12740. }
  12741. this._cache.rotation.copyFrom(this.rotation);
  12742. };
  12743. // Synchronized
  12744. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12745. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12746. return false;
  12747. }
  12748. var lockedTargetPosition = this._getLockedTargetPosition();
  12749. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12750. && this._cache.rotation.equals(this.rotation);
  12751. };
  12752. // Methods
  12753. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12754. var engine = this.getEngine();
  12755. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12756. };
  12757. // Target
  12758. TargetCamera.prototype.setTarget = function (target) {
  12759. this.upVector.normalize();
  12760. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12761. this._camMatrix.invert();
  12762. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12763. var vDir = target.subtract(this.position);
  12764. if (vDir.x >= 0.0) {
  12765. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12766. }
  12767. else {
  12768. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12769. }
  12770. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12771. if (isNaN(this.rotation.x)) {
  12772. this.rotation.x = 0;
  12773. }
  12774. if (isNaN(this.rotation.y)) {
  12775. this.rotation.y = 0;
  12776. }
  12777. if (isNaN(this.rotation.z)) {
  12778. this.rotation.z = 0;
  12779. }
  12780. };
  12781. TargetCamera.prototype.getTarget = function () {
  12782. return this._currentTarget;
  12783. };
  12784. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12785. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12786. };
  12787. TargetCamera.prototype._updatePosition = function () {
  12788. this.position.addInPlace(this.cameraDirection);
  12789. };
  12790. TargetCamera.prototype._checkInputs = function () {
  12791. var needToMove = this._decideIfNeedsToMove();
  12792. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12793. // Move
  12794. if (needToMove) {
  12795. this._updatePosition();
  12796. }
  12797. // Rotate
  12798. if (needToRotate) {
  12799. this.rotation.x += this.cameraRotation.x;
  12800. this.rotation.y += this.cameraRotation.y;
  12801. if (!this.noRotationConstraint) {
  12802. var limit = (Math.PI / 2) * 0.95;
  12803. if (this.rotation.x > limit)
  12804. this.rotation.x = limit;
  12805. if (this.rotation.x < -limit)
  12806. this.rotation.x = -limit;
  12807. }
  12808. }
  12809. // Inertia
  12810. if (needToMove) {
  12811. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12812. this.cameraDirection.x = 0;
  12813. }
  12814. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12815. this.cameraDirection.y = 0;
  12816. }
  12817. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12818. this.cameraDirection.z = 0;
  12819. }
  12820. this.cameraDirection.scaleInPlace(this.inertia);
  12821. }
  12822. if (needToRotate) {
  12823. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12824. this.cameraRotation.x = 0;
  12825. }
  12826. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12827. this.cameraRotation.y = 0;
  12828. }
  12829. this.cameraRotation.scaleInPlace(this.inertia);
  12830. }
  12831. _super.prototype._checkInputs.call(this);
  12832. };
  12833. TargetCamera.prototype._getViewMatrix = function () {
  12834. if (!this.lockedTarget) {
  12835. // Compute
  12836. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12837. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12838. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12839. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12840. this._lookAtTemp.invert();
  12841. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12842. }
  12843. else {
  12844. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12845. }
  12846. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12847. // Computing target and final matrix
  12848. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12849. }
  12850. else {
  12851. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12852. }
  12853. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12854. return this._viewMatrix;
  12855. };
  12856. TargetCamera.prototype._getVRViewMatrix = function () {
  12857. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12858. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12859. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12860. // Computing target and final matrix
  12861. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12862. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12863. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12864. return this._viewMatrix;
  12865. };
  12866. /**
  12867. * @override
  12868. * Override Camera.createRigCamera
  12869. */
  12870. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12871. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12872. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12873. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12874. rigCamera._cameraRigParams = {};
  12875. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12876. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12877. }
  12878. return rigCamera;
  12879. }
  12880. return null;
  12881. };
  12882. /**
  12883. * @override
  12884. * Override Camera._updateRigCameras
  12885. */
  12886. TargetCamera.prototype._updateRigCameras = function () {
  12887. switch (this.cameraRigMode) {
  12888. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12889. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12890. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12891. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12892. case BABYLON.Camera.RIG_MODE_VR:
  12893. var camLeft = this._rigCameras[0];
  12894. var camRight = this._rigCameras[1];
  12895. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12896. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12897. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12898. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12899. camLeft.position.copyFrom(this.position);
  12900. camRight.position.copyFrom(this.position);
  12901. }
  12902. else {
  12903. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12904. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12905. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12906. camLeft.setTarget(this.getTarget());
  12907. camRight.setTarget(this.getTarget());
  12908. }
  12909. break;
  12910. }
  12911. _super.prototype._updateRigCameras.call(this);
  12912. };
  12913. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12914. if (!this._rigCamTransformMatrix) {
  12915. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12916. }
  12917. var target = this.getTarget();
  12918. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12919. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12920. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12921. };
  12922. TargetCamera.prototype.getTypeName = function () {
  12923. return "TargetCamera";
  12924. };
  12925. __decorate([
  12926. BABYLON.serializeAsVector3()
  12927. ], TargetCamera.prototype, "rotation", void 0);
  12928. __decorate([
  12929. BABYLON.serialize()
  12930. ], TargetCamera.prototype, "speed", void 0);
  12931. __decorate([
  12932. BABYLON.serializeAsMeshReference("lockedTargetId")
  12933. ], TargetCamera.prototype, "lockedTarget", void 0);
  12934. return TargetCamera;
  12935. })(BABYLON.Camera);
  12936. BABYLON.TargetCamera = TargetCamera;
  12937. })(BABYLON || (BABYLON = {}));
  12938. var BABYLON;
  12939. (function (BABYLON) {
  12940. var FreeCamera = (function (_super) {
  12941. __extends(FreeCamera, _super);
  12942. function FreeCamera(name, position, scene) {
  12943. var _this = this;
  12944. _super.call(this, name, position, scene);
  12945. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12946. this.checkCollisions = false;
  12947. this.applyGravity = false;
  12948. this._collider = new BABYLON.Collider();
  12949. this._needMoveForGravity = false;
  12950. this._oldPosition = BABYLON.Vector3.Zero();
  12951. this._diffPosition = BABYLON.Vector3.Zero();
  12952. this._newPosition = BABYLON.Vector3.Zero();
  12953. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12954. if (collidedMesh === void 0) { collidedMesh = null; }
  12955. //TODO move this to the collision coordinator!
  12956. if (_this.getScene().workerCollisions)
  12957. newPosition.multiplyInPlace(_this._collider.radius);
  12958. var updatePosition = function (newPos) {
  12959. _this._newPosition.copyFrom(newPos);
  12960. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12961. var oldPosition = _this.position.clone();
  12962. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12963. _this.position.addInPlace(_this._diffPosition);
  12964. if (_this.onCollide && collidedMesh) {
  12965. _this.onCollide(collidedMesh);
  12966. }
  12967. }
  12968. };
  12969. updatePosition(newPosition);
  12970. };
  12971. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12972. this.inputs.addKeyboard().addMouse();
  12973. }
  12974. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12975. //-- begin properties for backward compatibility for inputs
  12976. get: function () {
  12977. var mouse = this.inputs.attached["mouse"];
  12978. if (mouse)
  12979. return mouse.angularSensibility;
  12980. },
  12981. set: function (value) {
  12982. var mouse = this.inputs.attached["mouse"];
  12983. if (mouse)
  12984. mouse.angularSensibility = value;
  12985. },
  12986. enumerable: true,
  12987. configurable: true
  12988. });
  12989. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12990. get: function () {
  12991. var keyboard = this.inputs.attached["keyboard"];
  12992. if (keyboard)
  12993. return keyboard.keysUp;
  12994. },
  12995. set: function (value) {
  12996. var keyboard = this.inputs.attached["keyboard"];
  12997. if (keyboard)
  12998. keyboard.keysUp = value;
  12999. },
  13000. enumerable: true,
  13001. configurable: true
  13002. });
  13003. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13004. get: function () {
  13005. var keyboard = this.inputs.attached["keyboard"];
  13006. if (keyboard)
  13007. return keyboard.keysDown;
  13008. },
  13009. set: function (value) {
  13010. var keyboard = this.inputs.attached["keyboard"];
  13011. if (keyboard)
  13012. keyboard.keysDown = value;
  13013. },
  13014. enumerable: true,
  13015. configurable: true
  13016. });
  13017. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13018. get: function () {
  13019. var keyboard = this.inputs.attached["keyboard"];
  13020. if (keyboard)
  13021. return keyboard.keysLeft;
  13022. },
  13023. set: function (value) {
  13024. var keyboard = this.inputs.attached["keyboard"];
  13025. if (keyboard)
  13026. keyboard.keysLeft = value;
  13027. },
  13028. enumerable: true,
  13029. configurable: true
  13030. });
  13031. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13032. get: function () {
  13033. var keyboard = this.inputs.attached["keyboard"];
  13034. if (keyboard)
  13035. return keyboard.keysRight;
  13036. },
  13037. set: function (value) {
  13038. var keyboard = this.inputs.attached["keyboard"];
  13039. if (keyboard)
  13040. keyboard.keysRight = value;
  13041. },
  13042. enumerable: true,
  13043. configurable: true
  13044. });
  13045. // Controls
  13046. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13047. this.inputs.attachElement(element, noPreventDefault);
  13048. };
  13049. FreeCamera.prototype.detachControl = function (element) {
  13050. this.inputs.detachElement(element);
  13051. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13052. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13053. };
  13054. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13055. var globalPosition;
  13056. if (this.parent) {
  13057. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13058. }
  13059. else {
  13060. globalPosition = this.position;
  13061. }
  13062. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13063. this._collider.radius = this.ellipsoid;
  13064. //no need for clone, as long as gravity is not on.
  13065. var actualVelocity = velocity;
  13066. //add gravity to the velocity to prevent the dual-collision checking
  13067. if (this.applyGravity) {
  13068. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13069. actualVelocity = velocity.add(this.getScene().gravity);
  13070. }
  13071. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13072. };
  13073. FreeCamera.prototype._checkInputs = function () {
  13074. if (!this._localDirection) {
  13075. this._localDirection = BABYLON.Vector3.Zero();
  13076. this._transformedDirection = BABYLON.Vector3.Zero();
  13077. }
  13078. this.inputs.checkInputs();
  13079. _super.prototype._checkInputs.call(this);
  13080. };
  13081. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13082. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13083. };
  13084. FreeCamera.prototype._updatePosition = function () {
  13085. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13086. this._collideWithWorld(this.cameraDirection);
  13087. }
  13088. else {
  13089. this.position.addInPlace(this.cameraDirection);
  13090. }
  13091. };
  13092. FreeCamera.prototype.dispose = function () {
  13093. this.inputs.clear();
  13094. _super.prototype.dispose.call(this);
  13095. };
  13096. FreeCamera.prototype.getTypeName = function () {
  13097. return "FreeCamera";
  13098. };
  13099. __decorate([
  13100. BABYLON.serializeAsVector3()
  13101. ], FreeCamera.prototype, "ellipsoid", void 0);
  13102. __decorate([
  13103. BABYLON.serialize()
  13104. ], FreeCamera.prototype, "checkCollisions", void 0);
  13105. __decorate([
  13106. BABYLON.serialize()
  13107. ], FreeCamera.prototype, "applyGravity", void 0);
  13108. return FreeCamera;
  13109. })(BABYLON.TargetCamera);
  13110. BABYLON.FreeCamera = FreeCamera;
  13111. })(BABYLON || (BABYLON = {}));
  13112. var BABYLON;
  13113. (function (BABYLON) {
  13114. var FreeCameraInputsManager = (function (_super) {
  13115. __extends(FreeCameraInputsManager, _super);
  13116. function FreeCameraInputsManager(camera) {
  13117. _super.call(this, camera);
  13118. }
  13119. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13120. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13121. return this;
  13122. };
  13123. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13124. if (touchEnabled === void 0) { touchEnabled = true; }
  13125. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13126. return this;
  13127. };
  13128. FreeCameraInputsManager.prototype.addGamepad = function () {
  13129. this.add(new BABYLON.FreeCameraGamepadInput());
  13130. return this;
  13131. };
  13132. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13133. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13134. return this;
  13135. };
  13136. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13137. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13138. return this;
  13139. };
  13140. FreeCameraInputsManager.prototype.addTouch = function () {
  13141. this.add(new BABYLON.FreeCameraTouchInput());
  13142. return this;
  13143. };
  13144. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13145. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13146. return this;
  13147. };
  13148. return FreeCameraInputsManager;
  13149. })(BABYLON.CameraInputsManager);
  13150. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13151. })(BABYLON || (BABYLON = {}));
  13152. var BABYLON;
  13153. (function (BABYLON) {
  13154. var FollowCamera = (function (_super) {
  13155. __extends(FollowCamera, _super);
  13156. function FollowCamera(name, position, scene, target) {
  13157. _super.call(this, name, position, scene);
  13158. this.radius = 12;
  13159. this.rotationOffset = 0;
  13160. this.heightOffset = 4;
  13161. this.cameraAcceleration = 0.05;
  13162. this.maxCameraSpeed = 20;
  13163. this.target = target;
  13164. }
  13165. FollowCamera.prototype.getRadians = function (degrees) {
  13166. return degrees * Math.PI / 180;
  13167. };
  13168. FollowCamera.prototype.follow = function (cameraTarget) {
  13169. if (!cameraTarget)
  13170. return;
  13171. var yRotation;
  13172. if (cameraTarget.rotationQuaternion) {
  13173. var rotMatrix = new BABYLON.Matrix();
  13174. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13175. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13176. }
  13177. else {
  13178. yRotation = cameraTarget.rotation.y;
  13179. }
  13180. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13181. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13182. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13183. var dx = targetX - this.position.x;
  13184. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13185. var dz = (targetZ) - this.position.z;
  13186. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13187. var vy = dy * this.cameraAcceleration;
  13188. var vz = dz * this.cameraAcceleration * 2;
  13189. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13190. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13191. }
  13192. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13193. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13194. }
  13195. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13196. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13197. }
  13198. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13199. this.setTarget(cameraTarget.position);
  13200. };
  13201. FollowCamera.prototype._checkInputs = function () {
  13202. _super.prototype._checkInputs.call(this);
  13203. this.follow(this.target);
  13204. };
  13205. FollowCamera.prototype.getTypeName = function () {
  13206. return "FollowCamera";
  13207. };
  13208. __decorate([
  13209. BABYLON.serialize()
  13210. ], FollowCamera.prototype, "radius", void 0);
  13211. __decorate([
  13212. BABYLON.serialize()
  13213. ], FollowCamera.prototype, "rotationOffset", void 0);
  13214. __decorate([
  13215. BABYLON.serialize()
  13216. ], FollowCamera.prototype, "heightOffset", void 0);
  13217. __decorate([
  13218. BABYLON.serialize()
  13219. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13220. __decorate([
  13221. BABYLON.serialize()
  13222. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13223. __decorate([
  13224. BABYLON.serializeAsMeshReference("lockedTargetId")
  13225. ], FollowCamera.prototype, "target", void 0);
  13226. return FollowCamera;
  13227. })(BABYLON.TargetCamera);
  13228. BABYLON.FollowCamera = FollowCamera;
  13229. var ArcFollowCamera = (function (_super) {
  13230. __extends(ArcFollowCamera, _super);
  13231. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13232. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13233. this.alpha = alpha;
  13234. this.beta = beta;
  13235. this.radius = radius;
  13236. this.target = target;
  13237. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13238. this.follow();
  13239. }
  13240. ArcFollowCamera.prototype.follow = function () {
  13241. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13242. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13243. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13244. this.position = this.target.position.add(this._cartesianCoordinates);
  13245. this.setTarget(this.target.position);
  13246. };
  13247. ArcFollowCamera.prototype._checkInputs = function () {
  13248. _super.prototype._checkInputs.call(this);
  13249. this.follow();
  13250. };
  13251. ArcFollowCamera.prototype.getTypeName = function () {
  13252. return "ArcFollowCamera";
  13253. };
  13254. return ArcFollowCamera;
  13255. })(BABYLON.TargetCamera);
  13256. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13257. })(BABYLON || (BABYLON = {}));
  13258. var BABYLON;
  13259. (function (BABYLON) {
  13260. // We're mainly based on the logic defined into the FreeCamera code
  13261. var TouchCamera = (function (_super) {
  13262. __extends(TouchCamera, _super);
  13263. //-- end properties for backward compatibility for inputs
  13264. function TouchCamera(name, position, scene) {
  13265. _super.call(this, name, position, scene);
  13266. this.inputs.addTouch();
  13267. this._setupInputs();
  13268. }
  13269. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13270. //-- Begin properties for backward compatibility for inputs
  13271. get: function () {
  13272. var touch = this.inputs.attached["touch"];
  13273. if (touch)
  13274. return touch.touchAngularSensibility;
  13275. },
  13276. set: function (value) {
  13277. var touch = this.inputs.attached["touch"];
  13278. if (touch)
  13279. touch.touchAngularSensibility = value;
  13280. },
  13281. enumerable: true,
  13282. configurable: true
  13283. });
  13284. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13285. get: function () {
  13286. var touch = this.inputs.attached["touch"];
  13287. if (touch)
  13288. return touch.touchMoveSensibility;
  13289. },
  13290. set: function (value) {
  13291. var touch = this.inputs.attached["touch"];
  13292. if (touch)
  13293. touch.touchMoveSensibility = value;
  13294. },
  13295. enumerable: true,
  13296. configurable: true
  13297. });
  13298. TouchCamera.prototype.getTypeName = function () {
  13299. return "TouchCamera";
  13300. };
  13301. TouchCamera.prototype._setupInputs = function () {
  13302. var mouse = this.inputs.attached["mouse"];
  13303. if (mouse) {
  13304. mouse.touchEnabled = false;
  13305. }
  13306. };
  13307. return TouchCamera;
  13308. })(BABYLON.FreeCamera);
  13309. BABYLON.TouchCamera = TouchCamera;
  13310. })(BABYLON || (BABYLON = {}));
  13311. var BABYLON;
  13312. (function (BABYLON) {
  13313. var ArcRotateCamera = (function (_super) {
  13314. __extends(ArcRotateCamera, _super);
  13315. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13316. var _this = this;
  13317. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13318. this.inertialAlphaOffset = 0;
  13319. this.inertialBetaOffset = 0;
  13320. this.inertialRadiusOffset = 0;
  13321. this.lowerAlphaLimit = null;
  13322. this.upperAlphaLimit = null;
  13323. this.lowerBetaLimit = 0.01;
  13324. this.upperBetaLimit = Math.PI;
  13325. this.lowerRadiusLimit = null;
  13326. this.upperRadiusLimit = null;
  13327. this.inertialPanningX = 0;
  13328. this.inertialPanningY = 0;
  13329. //-- end properties for backward compatibility for inputs
  13330. this.zoomOnFactor = 1;
  13331. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13332. this.allowUpsideDown = true;
  13333. this._viewMatrix = new BABYLON.Matrix();
  13334. // Panning
  13335. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13336. this.checkCollisions = false;
  13337. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13338. this._collider = new BABYLON.Collider();
  13339. this._previousPosition = BABYLON.Vector3.Zero();
  13340. this._collisionVelocity = BABYLON.Vector3.Zero();
  13341. this._newPosition = BABYLON.Vector3.Zero();
  13342. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13343. if (collidedMesh === void 0) { collidedMesh = null; }
  13344. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13345. newPosition.multiplyInPlace(_this._collider.radius);
  13346. }
  13347. if (!collidedMesh) {
  13348. _this._previousPosition.copyFrom(_this.position);
  13349. }
  13350. else {
  13351. _this.setPosition(newPosition);
  13352. if (_this.onCollide) {
  13353. _this.onCollide(collidedMesh);
  13354. }
  13355. }
  13356. // Recompute because of constraints
  13357. var cosa = Math.cos(_this.alpha);
  13358. var sina = Math.sin(_this.alpha);
  13359. var cosb = Math.cos(_this.beta);
  13360. var sinb = Math.sin(_this.beta);
  13361. if (sinb === 0) {
  13362. sinb = 0.0001;
  13363. }
  13364. var target = _this._getTargetPosition();
  13365. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13366. _this.position.copyFrom(_this._newPosition);
  13367. var up = _this.upVector;
  13368. if (_this.allowUpsideDown && _this.beta < 0) {
  13369. up = up.clone();
  13370. up = up.negate();
  13371. }
  13372. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13373. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13374. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13375. _this._collisionTriggered = false;
  13376. };
  13377. if (!target) {
  13378. this.target = BABYLON.Vector3.Zero();
  13379. }
  13380. else {
  13381. this.target = target;
  13382. }
  13383. this.alpha = alpha;
  13384. this.beta = beta;
  13385. this.radius = radius;
  13386. this.getViewMatrix();
  13387. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13388. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13389. }
  13390. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13391. //-- begin properties for backward compatibility for inputs
  13392. get: function () {
  13393. var pointers = this.inputs.attached["pointers"];
  13394. if (pointers)
  13395. return pointers.angularSensibilityX;
  13396. },
  13397. set: function (value) {
  13398. var pointers = this.inputs.attached["pointers"];
  13399. if (pointers) {
  13400. pointers.angularSensibilityX = value;
  13401. }
  13402. },
  13403. enumerable: true,
  13404. configurable: true
  13405. });
  13406. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13407. get: function () {
  13408. var pointers = this.inputs.attached["pointers"];
  13409. if (pointers)
  13410. return pointers.angularSensibilityY;
  13411. },
  13412. set: function (value) {
  13413. var pointers = this.inputs.attached["pointers"];
  13414. if (pointers) {
  13415. pointers.angularSensibilityY = value;
  13416. }
  13417. },
  13418. enumerable: true,
  13419. configurable: true
  13420. });
  13421. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13422. get: function () {
  13423. var pointers = this.inputs.attached["pointers"];
  13424. if (pointers)
  13425. return pointers.pinchPrecision;
  13426. },
  13427. set: function (value) {
  13428. var pointers = this.inputs.attached["pointers"];
  13429. if (pointers) {
  13430. pointers.pinchPrecision = value;
  13431. }
  13432. },
  13433. enumerable: true,
  13434. configurable: true
  13435. });
  13436. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13437. get: function () {
  13438. var pointers = this.inputs.attached["pointers"];
  13439. if (pointers)
  13440. return pointers.panningSensibility;
  13441. },
  13442. set: function (value) {
  13443. var pointers = this.inputs.attached["pointers"];
  13444. if (pointers) {
  13445. pointers.panningSensibility = value;
  13446. }
  13447. },
  13448. enumerable: true,
  13449. configurable: true
  13450. });
  13451. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13452. get: function () {
  13453. var keyboard = this.inputs.attached["keyboard"];
  13454. if (keyboard)
  13455. return keyboard.keysUp;
  13456. },
  13457. set: function (value) {
  13458. var keyboard = this.inputs.attached["keyboard"];
  13459. if (keyboard)
  13460. keyboard.keysUp = value;
  13461. },
  13462. enumerable: true,
  13463. configurable: true
  13464. });
  13465. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13466. get: function () {
  13467. var keyboard = this.inputs.attached["keyboard"];
  13468. if (keyboard)
  13469. return keyboard.keysDown;
  13470. },
  13471. set: function (value) {
  13472. var keyboard = this.inputs.attached["keyboard"];
  13473. if (keyboard)
  13474. keyboard.keysDown = value;
  13475. },
  13476. enumerable: true,
  13477. configurable: true
  13478. });
  13479. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13480. get: function () {
  13481. var keyboard = this.inputs.attached["keyboard"];
  13482. if (keyboard)
  13483. return keyboard.keysLeft;
  13484. },
  13485. set: function (value) {
  13486. var keyboard = this.inputs.attached["keyboard"];
  13487. if (keyboard)
  13488. keyboard.keysLeft = value;
  13489. },
  13490. enumerable: true,
  13491. configurable: true
  13492. });
  13493. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13494. get: function () {
  13495. var keyboard = this.inputs.attached["keyboard"];
  13496. if (keyboard)
  13497. return keyboard.keysRight;
  13498. },
  13499. set: function (value) {
  13500. var keyboard = this.inputs.attached["keyboard"];
  13501. if (keyboard)
  13502. keyboard.keysRight = value;
  13503. },
  13504. enumerable: true,
  13505. configurable: true
  13506. });
  13507. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13508. get: function () {
  13509. var mousewheel = this.inputs.attached["mousewheel"];
  13510. if (mousewheel)
  13511. return mousewheel.wheelPrecision;
  13512. },
  13513. set: function (value) {
  13514. var mousewheel = this.inputs.attached["mousewheel"];
  13515. if (mousewheel)
  13516. mousewheel.wheelPrecision = value;
  13517. },
  13518. enumerable: true,
  13519. configurable: true
  13520. });
  13521. // Cache
  13522. ArcRotateCamera.prototype._initCache = function () {
  13523. _super.prototype._initCache.call(this);
  13524. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13525. this._cache.alpha = undefined;
  13526. this._cache.beta = undefined;
  13527. this._cache.radius = undefined;
  13528. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13529. };
  13530. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13531. if (!ignoreParentClass) {
  13532. _super.prototype._updateCache.call(this);
  13533. }
  13534. this._cache.target.copyFrom(this._getTargetPosition());
  13535. this._cache.alpha = this.alpha;
  13536. this._cache.beta = this.beta;
  13537. this._cache.radius = this.radius;
  13538. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13539. };
  13540. ArcRotateCamera.prototype._getTargetPosition = function () {
  13541. if (this.target.getAbsolutePosition) {
  13542. return this.target.getAbsolutePosition();
  13543. }
  13544. return this.target;
  13545. };
  13546. // Synchronized
  13547. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13548. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13549. return false;
  13550. return this._cache.target.equals(this.target)
  13551. && this._cache.alpha === this.alpha
  13552. && this._cache.beta === this.beta
  13553. && this._cache.radius === this.radius
  13554. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13555. };
  13556. // Methods
  13557. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13558. var _this = this;
  13559. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13560. this._useCtrlForPanning = useCtrlForPanning;
  13561. this.inputs.attachElement(element, noPreventDefault);
  13562. this._reset = function () {
  13563. _this.inertialAlphaOffset = 0;
  13564. _this.inertialBetaOffset = 0;
  13565. _this.inertialRadiusOffset = 0;
  13566. };
  13567. };
  13568. ArcRotateCamera.prototype.detachControl = function (element) {
  13569. this.inputs.detachElement(element);
  13570. if (this._reset) {
  13571. this._reset();
  13572. }
  13573. };
  13574. ArcRotateCamera.prototype._checkInputs = function () {
  13575. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13576. if (this._collisionTriggered) {
  13577. return;
  13578. }
  13579. this.inputs.checkInputs();
  13580. // Inertia
  13581. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13582. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13583. this.beta += this.inertialBetaOffset;
  13584. this.radius -= this.inertialRadiusOffset;
  13585. this.inertialAlphaOffset *= this.inertia;
  13586. this.inertialBetaOffset *= this.inertia;
  13587. this.inertialRadiusOffset *= this.inertia;
  13588. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13589. this.inertialAlphaOffset = 0;
  13590. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13591. this.inertialBetaOffset = 0;
  13592. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13593. this.inertialRadiusOffset = 0;
  13594. }
  13595. // Panning inertia
  13596. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13597. if (!this._localDirection) {
  13598. this._localDirection = BABYLON.Vector3.Zero();
  13599. this._transformedDirection = BABYLON.Vector3.Zero();
  13600. }
  13601. this.inertialPanningX *= this.inertia;
  13602. this.inertialPanningY *= this.inertia;
  13603. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13604. this.inertialPanningX = 0;
  13605. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13606. this.inertialPanningY = 0;
  13607. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13608. this._localDirection.multiplyInPlace(this.panningAxis);
  13609. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13610. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13611. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13612. if (!this.panningAxis.y) {
  13613. this._transformedDirection.y = 0;
  13614. }
  13615. this.target.addInPlace(this._transformedDirection);
  13616. }
  13617. // Limits
  13618. this._checkLimits();
  13619. _super.prototype._checkInputs.call(this);
  13620. };
  13621. ArcRotateCamera.prototype._checkLimits = function () {
  13622. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13623. if (this.allowUpsideDown && this.beta > Math.PI) {
  13624. this.beta = this.beta - (2 * Math.PI);
  13625. }
  13626. }
  13627. else {
  13628. if (this.beta < this.lowerBetaLimit) {
  13629. this.beta = this.lowerBetaLimit;
  13630. }
  13631. }
  13632. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13633. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13634. this.beta = this.beta + (2 * Math.PI);
  13635. }
  13636. }
  13637. else {
  13638. if (this.beta > this.upperBetaLimit) {
  13639. this.beta = this.upperBetaLimit;
  13640. }
  13641. }
  13642. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13643. this.alpha = this.lowerAlphaLimit;
  13644. }
  13645. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13646. this.alpha = this.upperAlphaLimit;
  13647. }
  13648. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13649. this.radius = this.lowerRadiusLimit;
  13650. }
  13651. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13652. this.radius = this.upperRadiusLimit;
  13653. }
  13654. };
  13655. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13656. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13657. this.radius = radiusv3.length();
  13658. // Alpha
  13659. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13660. if (radiusv3.z < 0) {
  13661. this.alpha = 2 * Math.PI - this.alpha;
  13662. }
  13663. // Beta
  13664. this.beta = Math.acos(radiusv3.y / this.radius);
  13665. this._checkLimits();
  13666. };
  13667. ArcRotateCamera.prototype.setPosition = function (position) {
  13668. if (this.position.equals(position)) {
  13669. return;
  13670. }
  13671. this.position = position;
  13672. this.rebuildAnglesAndRadius();
  13673. };
  13674. ArcRotateCamera.prototype.setTarget = function (target) {
  13675. if (this._getTargetPosition().equals(target)) {
  13676. return;
  13677. }
  13678. this.target = target;
  13679. this.rebuildAnglesAndRadius();
  13680. };
  13681. ArcRotateCamera.prototype._getViewMatrix = function () {
  13682. // Compute
  13683. var cosa = Math.cos(this.alpha);
  13684. var sina = Math.sin(this.alpha);
  13685. var cosb = Math.cos(this.beta);
  13686. var sinb = Math.sin(this.beta);
  13687. if (sinb === 0) {
  13688. sinb = 0.0001;
  13689. }
  13690. var target = this._getTargetPosition();
  13691. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13692. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13693. this._collider.radius = this.collisionRadius;
  13694. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13695. this._collisionTriggered = true;
  13696. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13697. }
  13698. else {
  13699. this.position.copyFrom(this._newPosition);
  13700. var up = this.upVector;
  13701. if (this.allowUpsideDown && this.beta < 0) {
  13702. up = up.clone();
  13703. up = up.negate();
  13704. }
  13705. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13706. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13707. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13708. }
  13709. return this._viewMatrix;
  13710. };
  13711. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13712. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13713. meshes = meshes || this.getScene().meshes;
  13714. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13715. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13716. this.radius = distance * this.zoomOnFactor;
  13717. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13718. };
  13719. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13720. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13721. var meshesOrMinMaxVector;
  13722. var distance;
  13723. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13724. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13725. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13726. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13727. }
  13728. else {
  13729. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13730. distance = meshesOrMinMaxVectorAndDistance.distance;
  13731. }
  13732. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13733. if (!doNotUpdateMaxZ) {
  13734. this.maxZ = distance * 2;
  13735. }
  13736. };
  13737. /**
  13738. * @override
  13739. * Override Camera.createRigCamera
  13740. */
  13741. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13742. switch (this.cameraRigMode) {
  13743. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13744. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13745. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13746. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13747. case BABYLON.Camera.RIG_MODE_VR:
  13748. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13749. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13750. rigCam._cameraRigParams = {};
  13751. return rigCam;
  13752. }
  13753. return null;
  13754. };
  13755. /**
  13756. * @override
  13757. * Override Camera._updateRigCameras
  13758. */
  13759. ArcRotateCamera.prototype._updateRigCameras = function () {
  13760. switch (this.cameraRigMode) {
  13761. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13762. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13763. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13764. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13765. case BABYLON.Camera.RIG_MODE_VR:
  13766. var camLeft = this._rigCameras[0];
  13767. var camRight = this._rigCameras[1];
  13768. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13769. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13770. camLeft.beta = camRight.beta = this.beta;
  13771. camLeft.radius = camRight.radius = this.radius;
  13772. break;
  13773. }
  13774. _super.prototype._updateRigCameras.call(this);
  13775. };
  13776. ArcRotateCamera.prototype.dispose = function () {
  13777. this.inputs.clear();
  13778. _super.prototype.dispose.call(this);
  13779. };
  13780. ArcRotateCamera.prototype.getTypeName = function () {
  13781. return "ArcRotateCamera";
  13782. };
  13783. __decorate([
  13784. BABYLON.serialize()
  13785. ], ArcRotateCamera.prototype, "alpha", void 0);
  13786. __decorate([
  13787. BABYLON.serialize()
  13788. ], ArcRotateCamera.prototype, "beta", void 0);
  13789. __decorate([
  13790. BABYLON.serialize()
  13791. ], ArcRotateCamera.prototype, "radius", void 0);
  13792. __decorate([
  13793. BABYLON.serializeAsVector3()
  13794. ], ArcRotateCamera.prototype, "target", void 0);
  13795. __decorate([
  13796. BABYLON.serialize()
  13797. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13798. __decorate([
  13799. BABYLON.serialize()
  13800. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13801. __decorate([
  13802. BABYLON.serialize()
  13803. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13804. __decorate([
  13805. BABYLON.serialize()
  13806. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13807. __decorate([
  13808. BABYLON.serialize()
  13809. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13810. __decorate([
  13811. BABYLON.serialize()
  13812. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13813. __decorate([
  13814. BABYLON.serialize()
  13815. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13816. __decorate([
  13817. BABYLON.serialize()
  13818. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13819. __decorate([
  13820. BABYLON.serialize()
  13821. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13822. __decorate([
  13823. BABYLON.serialize()
  13824. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13825. __decorate([
  13826. BABYLON.serialize()
  13827. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13828. __decorate([
  13829. BABYLON.serialize()
  13830. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13831. __decorate([
  13832. BABYLON.serialize()
  13833. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13834. return ArcRotateCamera;
  13835. })(BABYLON.TargetCamera);
  13836. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13837. })(BABYLON || (BABYLON = {}));
  13838. var BABYLON;
  13839. (function (BABYLON) {
  13840. var ArcRotateCameraInputsManager = (function (_super) {
  13841. __extends(ArcRotateCameraInputsManager, _super);
  13842. function ArcRotateCameraInputsManager(camera) {
  13843. _super.call(this, camera);
  13844. }
  13845. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13846. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13847. return this;
  13848. };
  13849. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13850. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13851. return this;
  13852. };
  13853. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13854. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13855. return this;
  13856. };
  13857. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13858. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13859. return this;
  13860. };
  13861. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13862. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13863. return this;
  13864. };
  13865. return ArcRotateCameraInputsManager;
  13866. })(BABYLON.CameraInputsManager);
  13867. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13868. })(BABYLON || (BABYLON = {}));
  13869. var BABYLON;
  13870. (function (BABYLON) {
  13871. var RenderingManager = (function () {
  13872. function RenderingManager(scene) {
  13873. this._renderingGroups = new Array();
  13874. this._scene = scene;
  13875. }
  13876. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13877. if (this._scene._activeParticleSystems.length === 0) {
  13878. return;
  13879. }
  13880. // Particles
  13881. var activeCamera = this._scene.activeCamera;
  13882. var beforeParticlesDate = BABYLON.Tools.Now;
  13883. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13884. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13885. if (particleSystem.renderingGroupId !== index) {
  13886. continue;
  13887. }
  13888. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13889. continue;
  13890. }
  13891. this._clearDepthBuffer();
  13892. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13893. this._scene._activeParticles += particleSystem.render();
  13894. }
  13895. }
  13896. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13897. };
  13898. RenderingManager.prototype._renderSprites = function (index) {
  13899. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13900. return;
  13901. }
  13902. // Sprites
  13903. var activeCamera = this._scene.activeCamera;
  13904. var beforeSpritessDate = BABYLON.Tools.Now;
  13905. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13906. var spriteManager = this._scene.spriteManagers[id];
  13907. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13908. this._clearDepthBuffer();
  13909. spriteManager.render();
  13910. }
  13911. }
  13912. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13913. };
  13914. RenderingManager.prototype._clearDepthBuffer = function () {
  13915. if (this._depthBufferAlreadyCleaned) {
  13916. return;
  13917. }
  13918. this._scene.getEngine().clear(0, false, true);
  13919. this._depthBufferAlreadyCleaned = true;
  13920. };
  13921. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13922. if (this._currentRenderSprites) {
  13923. this._renderSprites(this._currentIndex);
  13924. }
  13925. if (this._currentRenderParticles) {
  13926. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13927. }
  13928. };
  13929. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13930. this._currentActiveMeshes = activeMeshes;
  13931. this._currentRenderParticles = renderParticles;
  13932. this._currentRenderSprites = renderSprites;
  13933. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13934. this._depthBufferAlreadyCleaned = index == 0;
  13935. var renderingGroup = this._renderingGroups[index];
  13936. var needToStepBack = false;
  13937. this._currentIndex = index;
  13938. if (renderingGroup) {
  13939. this._clearDepthBuffer();
  13940. if (!renderingGroup.onBeforeTransparentRendering) {
  13941. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13942. }
  13943. if (!renderingGroup.render(customRenderFunction)) {
  13944. this._renderingGroups.splice(index, 1);
  13945. needToStepBack = true;
  13946. this._renderSpritesAndParticles();
  13947. }
  13948. }
  13949. else {
  13950. this._renderSpritesAndParticles();
  13951. }
  13952. if (needToStepBack) {
  13953. index--;
  13954. }
  13955. }
  13956. };
  13957. RenderingManager.prototype.reset = function () {
  13958. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13959. if (renderingGroup) {
  13960. renderingGroup.prepare();
  13961. }
  13962. });
  13963. };
  13964. RenderingManager.prototype.dispatch = function (subMesh) {
  13965. var mesh = subMesh.getMesh();
  13966. var renderingGroupId = mesh.renderingGroupId || 0;
  13967. if (!this._renderingGroups[renderingGroupId]) {
  13968. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13969. }
  13970. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13971. };
  13972. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13973. return RenderingManager;
  13974. })();
  13975. BABYLON.RenderingManager = RenderingManager;
  13976. })(BABYLON || (BABYLON = {}));
  13977. var BABYLON;
  13978. (function (BABYLON) {
  13979. var RenderingGroup = (function () {
  13980. function RenderingGroup(index, scene) {
  13981. this.index = index;
  13982. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13983. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13984. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13985. this._scene = scene;
  13986. }
  13987. RenderingGroup.prototype.render = function (customRenderFunction) {
  13988. if (customRenderFunction) {
  13989. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13990. return true;
  13991. }
  13992. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13993. if (this.onBeforeTransparentRendering) {
  13994. this.onBeforeTransparentRendering();
  13995. }
  13996. return false;
  13997. }
  13998. var engine = this._scene.getEngine();
  13999. // Opaque
  14000. var subIndex;
  14001. var submesh;
  14002. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14003. submesh = this._opaqueSubMeshes.data[subIndex];
  14004. submesh.render(false);
  14005. }
  14006. // Alpha test
  14007. engine.setAlphaTesting(true);
  14008. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14009. submesh = this._alphaTestSubMeshes.data[subIndex];
  14010. submesh.render(false);
  14011. }
  14012. engine.setAlphaTesting(false);
  14013. if (this.onBeforeTransparentRendering) {
  14014. this.onBeforeTransparentRendering();
  14015. }
  14016. // Transparent
  14017. if (this._transparentSubMeshes.length) {
  14018. // Sorting
  14019. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14020. submesh = this._transparentSubMeshes.data[subIndex];
  14021. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14022. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14023. }
  14024. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14025. sortedArray.sort(function (a, b) {
  14026. // Alpha index first
  14027. if (a._alphaIndex > b._alphaIndex) {
  14028. return 1;
  14029. }
  14030. if (a._alphaIndex < b._alphaIndex) {
  14031. return -1;
  14032. }
  14033. // Then distance to camera
  14034. if (a._distanceToCamera < b._distanceToCamera) {
  14035. return 1;
  14036. }
  14037. if (a._distanceToCamera > b._distanceToCamera) {
  14038. return -1;
  14039. }
  14040. return 0;
  14041. });
  14042. // Rendering
  14043. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14044. submesh = sortedArray[subIndex];
  14045. submesh.render(true);
  14046. }
  14047. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14048. }
  14049. return true;
  14050. };
  14051. RenderingGroup.prototype.prepare = function () {
  14052. this._opaqueSubMeshes.reset();
  14053. this._transparentSubMeshes.reset();
  14054. this._alphaTestSubMeshes.reset();
  14055. };
  14056. RenderingGroup.prototype.dispatch = function (subMesh) {
  14057. var material = subMesh.getMaterial();
  14058. var mesh = subMesh.getMesh();
  14059. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14060. this._transparentSubMeshes.push(subMesh);
  14061. }
  14062. else if (material.needAlphaTesting()) {
  14063. this._alphaTestSubMeshes.push(subMesh);
  14064. }
  14065. else {
  14066. this._opaqueSubMeshes.push(subMesh); // Opaque
  14067. }
  14068. };
  14069. return RenderingGroup;
  14070. })();
  14071. BABYLON.RenderingGroup = RenderingGroup;
  14072. })(BABYLON || (BABYLON = {}));
  14073. var BABYLON;
  14074. (function (BABYLON) {
  14075. var PointerEventTypes = (function () {
  14076. function PointerEventTypes() {
  14077. }
  14078. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14079. get: function () {
  14080. return PointerEventTypes._POINTERDOWN;
  14081. },
  14082. enumerable: true,
  14083. configurable: true
  14084. });
  14085. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14086. get: function () {
  14087. return PointerEventTypes._POINTERUP;
  14088. },
  14089. enumerable: true,
  14090. configurable: true
  14091. });
  14092. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14093. get: function () {
  14094. return PointerEventTypes._POINTERMOVE;
  14095. },
  14096. enumerable: true,
  14097. configurable: true
  14098. });
  14099. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14100. get: function () {
  14101. return PointerEventTypes._POINTERWHEEL;
  14102. },
  14103. enumerable: true,
  14104. configurable: true
  14105. });
  14106. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14107. get: function () {
  14108. return PointerEventTypes._POINTERPICK;
  14109. },
  14110. enumerable: true,
  14111. configurable: true
  14112. });
  14113. PointerEventTypes._POINTERDOWN = 0x01;
  14114. PointerEventTypes._POINTERUP = 0x02;
  14115. PointerEventTypes._POINTERMOVE = 0x04;
  14116. PointerEventTypes._POINTERWHEEL = 0x08;
  14117. PointerEventTypes._POINTERPICK = 0x10;
  14118. return PointerEventTypes;
  14119. })();
  14120. BABYLON.PointerEventTypes = PointerEventTypes;
  14121. /**
  14122. * This type contains all the data related to a pointer event in Babylon.js.
  14123. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The differents event types can be found in the PointerEventTypes class.
  14124. */
  14125. var PointerInfo = (function () {
  14126. function PointerInfo(type, event, pickInfo) {
  14127. this.type = type;
  14128. this.event = event;
  14129. this.pickInfo = pickInfo;
  14130. }
  14131. return PointerInfo;
  14132. })();
  14133. BABYLON.PointerInfo = PointerInfo;
  14134. /**
  14135. * Represents a scene to be rendered by the engine.
  14136. * @see http://doc.babylonjs.com/page.php?p=21911
  14137. */
  14138. var Scene = (function () {
  14139. /**
  14140. * @constructor
  14141. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14142. */
  14143. function Scene(engine) {
  14144. // Members
  14145. this.autoClear = true;
  14146. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14147. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14148. this.forceWireframe = false;
  14149. this.forcePointsCloud = false;
  14150. this.forceShowBoundingBoxes = false;
  14151. this.animationsEnabled = true;
  14152. this.constantlyUpdateMeshUnderPointer = false;
  14153. // Events
  14154. /**
  14155. * An event triggered when the scene is disposed.
  14156. * @type {BABYLON.Observable}
  14157. */
  14158. this.onDisposeObservable = new BABYLON.Observable();
  14159. /**
  14160. * An event triggered before rendering the scene
  14161. * @type {BABYLON.Observable}
  14162. */
  14163. this.onBeforeRenderObservable = new BABYLON.Observable();
  14164. /**
  14165. * An event triggered after rendering the scene
  14166. * @type {BABYLON.Observable}
  14167. */
  14168. this.onAfterRenderObservable = new BABYLON.Observable();
  14169. /**
  14170. * An event triggered when the scene is ready
  14171. * @type {BABYLON.Observable}
  14172. */
  14173. this.onReadyObservable = new BABYLON.Observable();
  14174. /**
  14175. * An event triggered before rendering a camera
  14176. * @type {BABYLON.Observable}
  14177. */
  14178. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14179. /**
  14180. * An event triggered after rendering a camera
  14181. * @type {BABYLON.Observable}
  14182. */
  14183. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14184. /**
  14185. * An event triggered when a camera is created
  14186. * @type {BABYLON.Observable}
  14187. */
  14188. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14189. /**
  14190. * An event triggered when a camera is removed
  14191. * @type {BABYLON.Observable}
  14192. */
  14193. this.onCameraRemovedObservable = new BABYLON.Observable();
  14194. /**
  14195. * An event triggered when a light is created
  14196. * @type {BABYLON.Observable}
  14197. */
  14198. this.onNewLightAddedObservable = new BABYLON.Observable();
  14199. /**
  14200. * An event triggered when a light is removed
  14201. * @type {BABYLON.Observable}
  14202. */
  14203. this.onLightRemovedObservable = new BABYLON.Observable();
  14204. /**
  14205. * An event triggered when a geometry is created
  14206. * @type {BABYLON.Observable}
  14207. */
  14208. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14209. /**
  14210. * An event triggered when a geometry is removed
  14211. * @type {BABYLON.Observable}
  14212. */
  14213. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14214. /**
  14215. * An event triggered when a mesh is created
  14216. * @type {BABYLON.Observable}
  14217. */
  14218. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14219. /**
  14220. * An event triggered when a mesh is removed
  14221. * @type {BABYLON.Observable}
  14222. */
  14223. this.onMeshRemovedObservable = new BABYLON.Observable();
  14224. // Animations
  14225. this.animations = [];
  14226. /**
  14227. * Observable event triggered each time an input event is received from the rendering canvas
  14228. */
  14229. this.onPointerObservable = new BABYLON.Observable();
  14230. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  14231. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14232. this._startingPointerTime = 0;
  14233. // Fog
  14234. /**
  14235. * is fog enabled on this scene.
  14236. * @type {boolean}
  14237. */
  14238. this.fogEnabled = true;
  14239. this.fogMode = Scene.FOGMODE_NONE;
  14240. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14241. this.fogDensity = 0.1;
  14242. this.fogStart = 0;
  14243. this.fogEnd = 1000.0;
  14244. // Lights
  14245. /**
  14246. * is shadow enabled on this scene.
  14247. * @type {boolean}
  14248. */
  14249. this.shadowsEnabled = true;
  14250. /**
  14251. * is light enabled on this scene.
  14252. * @type {boolean}
  14253. */
  14254. this.lightsEnabled = true;
  14255. /**
  14256. * All of the lights added to this scene.
  14257. * @see BABYLON.Light
  14258. * @type {BABYLON.Light[]}
  14259. */
  14260. this.lights = new Array();
  14261. // Cameras
  14262. /**
  14263. * All of the cameras added to this scene.
  14264. * @see BABYLON.Camera
  14265. * @type {BABYLON.Camera[]}
  14266. */
  14267. this.cameras = new Array();
  14268. this.activeCameras = new Array();
  14269. // Meshes
  14270. /**
  14271. * All of the (abstract) meshes added to this scene.
  14272. * @see BABYLON.AbstractMesh
  14273. * @type {BABYLON.AbstractMesh[]}
  14274. */
  14275. this.meshes = new Array();
  14276. // Geometries
  14277. this._geometries = new Array();
  14278. this.materials = new Array();
  14279. this.multiMaterials = new Array();
  14280. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14281. // Textures
  14282. this.texturesEnabled = true;
  14283. this.textures = new Array();
  14284. // Particles
  14285. this.particlesEnabled = true;
  14286. this.particleSystems = new Array();
  14287. // Sprites
  14288. this.spritesEnabled = true;
  14289. this.spriteManagers = new Array();
  14290. // Layers
  14291. this.layers = new Array();
  14292. // Skeletons
  14293. this.skeletonsEnabled = true;
  14294. this.skeletons = new Array();
  14295. // Lens flares
  14296. this.lensFlaresEnabled = true;
  14297. this.lensFlareSystems = new Array();
  14298. // Collisions
  14299. this.collisionsEnabled = true;
  14300. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14301. // Postprocesses
  14302. this.postProcessesEnabled = true;
  14303. // Customs render targets
  14304. this.renderTargetsEnabled = true;
  14305. this.dumpNextRenderTargets = false;
  14306. this.customRenderTargets = new Array();
  14307. // Imported meshes
  14308. this.importedMeshesFiles = new Array();
  14309. // Probes
  14310. this.probesEnabled = true;
  14311. this.reflectionProbes = new Array();
  14312. this._actionManagers = new Array();
  14313. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14314. // Procedural textures
  14315. this.proceduralTexturesEnabled = true;
  14316. this._proceduralTextures = new Array();
  14317. this.soundTracks = new Array();
  14318. this._audioEnabled = true;
  14319. this._headphone = false;
  14320. this._totalVertices = 0;
  14321. this._activeIndices = 0;
  14322. this._activeParticles = 0;
  14323. this._lastFrameDuration = 0;
  14324. this._evaluateActiveMeshesDuration = 0;
  14325. this._renderTargetsDuration = 0;
  14326. this._particlesDuration = 0;
  14327. this._renderDuration = 0;
  14328. this._spritesDuration = 0;
  14329. this._animationRatio = 0;
  14330. this._renderId = 0;
  14331. this._executeWhenReadyTimeoutId = -1;
  14332. this._intermediateRendering = false;
  14333. this._toBeDisposed = new BABYLON.SmartArray(256);
  14334. this._pendingData = []; //ANY
  14335. this._activeMeshes = new BABYLON.SmartArray(256);
  14336. this._processedMaterials = new BABYLON.SmartArray(256);
  14337. this._renderTargets = new BABYLON.SmartArray(256);
  14338. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14339. this._activeSkeletons = new BABYLON.SmartArray(32);
  14340. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14341. this._activeBones = 0;
  14342. this._activeAnimatables = new Array();
  14343. this._transformMatrix = BABYLON.Matrix.Zero();
  14344. this._edgesRenderers = new BABYLON.SmartArray(16);
  14345. this._uniqueIdCounter = 0;
  14346. this._engine = engine;
  14347. engine.scenes.push(this);
  14348. this._renderingManager = new BABYLON.RenderingManager(this);
  14349. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14350. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14351. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14352. if (BABYLON.OutlineRenderer) {
  14353. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14354. }
  14355. this.attachControl();
  14356. this._debugLayer = new BABYLON.DebugLayer(this);
  14357. if (BABYLON.SoundTrack) {
  14358. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14359. }
  14360. //simplification queue
  14361. if (BABYLON.SimplificationQueue) {
  14362. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14363. }
  14364. //collision coordinator initialization. For now legacy per default.
  14365. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14366. }
  14367. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14368. get: function () {
  14369. return Scene._FOGMODE_NONE;
  14370. },
  14371. enumerable: true,
  14372. configurable: true
  14373. });
  14374. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14375. get: function () {
  14376. return Scene._FOGMODE_EXP;
  14377. },
  14378. enumerable: true,
  14379. configurable: true
  14380. });
  14381. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14382. get: function () {
  14383. return Scene._FOGMODE_EXP2;
  14384. },
  14385. enumerable: true,
  14386. configurable: true
  14387. });
  14388. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14389. get: function () {
  14390. return Scene._FOGMODE_LINEAR;
  14391. },
  14392. enumerable: true,
  14393. configurable: true
  14394. });
  14395. Object.defineProperty(Scene.prototype, "onDispose", {
  14396. set: function (callback) {
  14397. if (this._onDisposeObserver) {
  14398. this.onDisposeObservable.remove(this._onDisposeObserver);
  14399. }
  14400. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14401. },
  14402. enumerable: true,
  14403. configurable: true
  14404. });
  14405. Object.defineProperty(Scene.prototype, "beforeRender", {
  14406. set: function (callback) {
  14407. if (this._onBeforeRenderObserver) {
  14408. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14409. }
  14410. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14411. },
  14412. enumerable: true,
  14413. configurable: true
  14414. });
  14415. Object.defineProperty(Scene.prototype, "afterRender", {
  14416. set: function (callback) {
  14417. if (this._onAfterRenderObserver) {
  14418. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14419. }
  14420. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14421. },
  14422. enumerable: true,
  14423. configurable: true
  14424. });
  14425. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14426. set: function (callback) {
  14427. if (this._onBeforeCameraRenderObserver) {
  14428. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14429. }
  14430. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14431. },
  14432. enumerable: true,
  14433. configurable: true
  14434. });
  14435. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14436. set: function (callback) {
  14437. if (this._onAfterCameraRenderObserver) {
  14438. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14439. }
  14440. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14441. },
  14442. enumerable: true,
  14443. configurable: true
  14444. });
  14445. Object.defineProperty(Scene.prototype, "debugLayer", {
  14446. // Properties
  14447. get: function () {
  14448. return this._debugLayer;
  14449. },
  14450. enumerable: true,
  14451. configurable: true
  14452. });
  14453. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14454. get: function () {
  14455. return this._workerCollisions;
  14456. },
  14457. set: function (enabled) {
  14458. enabled = (enabled && !!Worker);
  14459. this._workerCollisions = enabled;
  14460. if (this.collisionCoordinator) {
  14461. this.collisionCoordinator.destroy();
  14462. }
  14463. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14464. this.collisionCoordinator.init(this);
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14470. get: function () {
  14471. return this._selectionOctree;
  14472. },
  14473. enumerable: true,
  14474. configurable: true
  14475. });
  14476. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14477. /**
  14478. * The mesh that is currently under the pointer.
  14479. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14480. */
  14481. get: function () {
  14482. return this._pointerOverMesh;
  14483. },
  14484. enumerable: true,
  14485. configurable: true
  14486. });
  14487. Object.defineProperty(Scene.prototype, "pointerX", {
  14488. /**
  14489. * Current on-screen X position of the pointer
  14490. * @return {number} X position of the pointer
  14491. */
  14492. get: function () {
  14493. return this._pointerX;
  14494. },
  14495. enumerable: true,
  14496. configurable: true
  14497. });
  14498. Object.defineProperty(Scene.prototype, "pointerY", {
  14499. /**
  14500. * Current on-screen Y position of the pointer
  14501. * @return {number} Y position of the pointer
  14502. */
  14503. get: function () {
  14504. return this._pointerY;
  14505. },
  14506. enumerable: true,
  14507. configurable: true
  14508. });
  14509. Scene.prototype.getCachedMaterial = function () {
  14510. return this._cachedMaterial;
  14511. };
  14512. Scene.prototype.getBoundingBoxRenderer = function () {
  14513. return this._boundingBoxRenderer;
  14514. };
  14515. Scene.prototype.getOutlineRenderer = function () {
  14516. return this._outlineRenderer;
  14517. };
  14518. Scene.prototype.getEngine = function () {
  14519. return this._engine;
  14520. };
  14521. Scene.prototype.getTotalVertices = function () {
  14522. return this._totalVertices;
  14523. };
  14524. Scene.prototype.getActiveIndices = function () {
  14525. return this._activeIndices;
  14526. };
  14527. Scene.prototype.getActiveParticles = function () {
  14528. return this._activeParticles;
  14529. };
  14530. Scene.prototype.getActiveBones = function () {
  14531. return this._activeBones;
  14532. };
  14533. // Stats
  14534. Scene.prototype.getLastFrameDuration = function () {
  14535. return this._lastFrameDuration;
  14536. };
  14537. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14538. return this._evaluateActiveMeshesDuration;
  14539. };
  14540. Scene.prototype.getActiveMeshes = function () {
  14541. return this._activeMeshes;
  14542. };
  14543. Scene.prototype.getRenderTargetsDuration = function () {
  14544. return this._renderTargetsDuration;
  14545. };
  14546. Scene.prototype.getRenderDuration = function () {
  14547. return this._renderDuration;
  14548. };
  14549. Scene.prototype.getParticlesDuration = function () {
  14550. return this._particlesDuration;
  14551. };
  14552. Scene.prototype.getSpritesDuration = function () {
  14553. return this._spritesDuration;
  14554. };
  14555. Scene.prototype.getAnimationRatio = function () {
  14556. return this._animationRatio;
  14557. };
  14558. Scene.prototype.getRenderId = function () {
  14559. return this._renderId;
  14560. };
  14561. Scene.prototype.incrementRenderId = function () {
  14562. this._renderId++;
  14563. };
  14564. Scene.prototype._updatePointerPosition = function (evt) {
  14565. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14566. this._pointerX = evt.clientX - canvasRect.left;
  14567. this._pointerY = evt.clientY - canvasRect.top;
  14568. this._unTranslatedPointerX = this._pointerX;
  14569. this._unTranslatedPointerY = this._pointerY;
  14570. if (this.cameraToUseForPointers) {
  14571. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14572. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14573. }
  14574. };
  14575. // Pointers handling
  14576. /**
  14577. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14578. * @param attachUp defines if you want to attach events to pointerup
  14579. * @param attachDown defines if you want to attach events to pointerdown
  14580. * @param attachMove defines if you want to attach events to pointermove
  14581. */
  14582. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14583. var _this = this;
  14584. if (attachUp === void 0) { attachUp = true; }
  14585. if (attachDown === void 0) { attachDown = true; }
  14586. if (attachMove === void 0) { attachMove = true; }
  14587. var spritePredicate = function (sprite) {
  14588. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14589. };
  14590. this._onPointerMove = function (evt) {
  14591. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14592. return;
  14593. }
  14594. var canvas = _this._engine.getRenderingCanvas();
  14595. _this._updatePointerPosition(evt);
  14596. if (!_this.pointerMovePredicate) {
  14597. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14598. }
  14599. // Meshes
  14600. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14601. if (pickResult.hit && pickResult.pickedMesh) {
  14602. _this.setPointerOverSprite(null);
  14603. _this.setPointerOverMesh(pickResult.pickedMesh);
  14604. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14605. canvas.style.cursor = "pointer";
  14606. }
  14607. else {
  14608. canvas.style.cursor = "";
  14609. }
  14610. }
  14611. else {
  14612. _this.setPointerOverMesh(null);
  14613. // Sprites
  14614. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14615. if (pickResult.hit && pickResult.pickedSprite) {
  14616. canvas.style.cursor = "pointer";
  14617. _this.setPointerOverSprite(pickResult.pickedSprite);
  14618. }
  14619. else {
  14620. _this.setPointerOverSprite(null);
  14621. // Restore pointer
  14622. canvas.style.cursor = "";
  14623. }
  14624. }
  14625. if (_this.onPointerMove) {
  14626. _this.onPointerMove(evt, pickResult);
  14627. }
  14628. if (_this.onPointerObservable.hasObservers()) {
  14629. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14630. var pi = new PointerInfo(type, evt, pickResult);
  14631. _this.onPointerObservable.notifyObservers(pi, type);
  14632. }
  14633. };
  14634. this._onPointerDown = function (evt) {
  14635. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14636. return;
  14637. }
  14638. _this._updatePointerPosition(evt);
  14639. _this._startingPointerPosition.x = _this._pointerX;
  14640. _this._startingPointerPosition.y = _this._pointerY;
  14641. _this._startingPointerTime = new Date().getTime();
  14642. if (!_this.pointerDownPredicate) {
  14643. _this.pointerDownPredicate = function (mesh) {
  14644. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14645. };
  14646. }
  14647. // Meshes
  14648. _this._pickedDownMesh = null;
  14649. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14650. if (pickResult.hit && pickResult.pickedMesh) {
  14651. if (pickResult.pickedMesh.actionManager) {
  14652. _this._pickedDownMesh = pickResult.pickedMesh;
  14653. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14654. switch (evt.button) {
  14655. case 0:
  14656. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14657. break;
  14658. case 1:
  14659. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14660. break;
  14661. case 2:
  14662. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14663. break;
  14664. }
  14665. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14666. }
  14667. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14668. var that = _this;
  14669. window.setTimeout(function () {
  14670. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  14671. if (pickResult.hit && pickResult.pickedMesh) {
  14672. if (pickResult.pickedMesh.actionManager) {
  14673. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  14674. that._startingPointerTime = 0;
  14675. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14676. }
  14677. }
  14678. }
  14679. }, BABYLON.ActionManager.LongPressDelay);
  14680. }
  14681. }
  14682. }
  14683. if (_this.onPointerDown) {
  14684. _this.onPointerDown(evt, pickResult);
  14685. }
  14686. if (_this.onPointerObservable.hasObservers()) {
  14687. var type = PointerEventTypes.POINTERDOWN;
  14688. var pi = new PointerInfo(type, evt, pickResult);
  14689. _this.onPointerObservable.notifyObservers(pi, type);
  14690. }
  14691. // Sprites
  14692. _this._pickedDownSprite = null;
  14693. if (_this.spriteManagers.length > 0) {
  14694. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14695. if (pickResult.hit && pickResult.pickedSprite) {
  14696. if (pickResult.pickedSprite.actionManager) {
  14697. _this._pickedDownSprite = pickResult.pickedSprite;
  14698. switch (evt.button) {
  14699. case 0:
  14700. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14701. break;
  14702. case 1:
  14703. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14704. break;
  14705. case 2:
  14706. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14707. break;
  14708. }
  14709. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14710. }
  14711. }
  14712. }
  14713. };
  14714. this._onPointerUp = function (evt) {
  14715. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14716. return;
  14717. }
  14718. _this._updatePointerPosition(evt);
  14719. if (!_this.pointerUpPredicate) {
  14720. _this.pointerUpPredicate = function (mesh) {
  14721. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14722. };
  14723. }
  14724. // Meshes
  14725. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14726. if (pickResult.hit && pickResult.pickedMesh) {
  14727. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14728. if (_this.onPointerPick) {
  14729. _this.onPointerPick(evt, pickResult);
  14730. }
  14731. if (_this.onPointerObservable.hasObservers()) {
  14732. var type = PointerEventTypes.POINTERPICK;
  14733. var pi = new PointerInfo(type, evt, pickResult);
  14734. _this.onPointerObservable.notifyObservers(pi, type);
  14735. }
  14736. }
  14737. if (pickResult.pickedMesh.actionManager) {
  14738. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14739. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14740. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14741. }
  14742. }
  14743. }
  14744. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14745. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14746. }
  14747. if (_this.onPointerUp) {
  14748. _this.onPointerUp(evt, pickResult);
  14749. }
  14750. if (_this.onPointerObservable.hasObservers()) {
  14751. var type = PointerEventTypes.POINTERUP;
  14752. var pi = new PointerInfo(type, evt, pickResult);
  14753. _this.onPointerObservable.notifyObservers(pi, type);
  14754. }
  14755. _this._startingPointerTime = 0;
  14756. // Sprites
  14757. if (_this.spriteManagers.length > 0) {
  14758. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14759. if (pickResult.hit && pickResult.pickedSprite) {
  14760. if (pickResult.pickedSprite.actionManager) {
  14761. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14762. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14763. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14764. }
  14765. }
  14766. }
  14767. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14768. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14769. }
  14770. }
  14771. };
  14772. this._onKeyDown = function (evt) {
  14773. if (_this.actionManager) {
  14774. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14775. }
  14776. };
  14777. this._onKeyUp = function (evt) {
  14778. if (_this.actionManager) {
  14779. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14780. }
  14781. };
  14782. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14783. if (attachMove) {
  14784. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14785. // Wheel
  14786. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14787. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14788. }
  14789. if (attachDown) {
  14790. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14791. }
  14792. if (attachUp) {
  14793. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14794. }
  14795. BABYLON.Tools.RegisterTopRootEvents([
  14796. { name: "keydown", handler: this._onKeyDown },
  14797. { name: "keyup", handler: this._onKeyUp }
  14798. ]);
  14799. };
  14800. Scene.prototype.detachControl = function () {
  14801. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14802. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14803. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14804. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14805. // Wheel
  14806. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14807. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14808. BABYLON.Tools.UnregisterTopRootEvents([
  14809. { name: "keydown", handler: this._onKeyDown },
  14810. { name: "keyup", handler: this._onKeyUp }
  14811. ]);
  14812. };
  14813. // Ready
  14814. Scene.prototype.isReady = function () {
  14815. if (this._pendingData.length > 0) {
  14816. return false;
  14817. }
  14818. var index;
  14819. for (index = 0; index < this._geometries.length; index++) {
  14820. var geometry = this._geometries[index];
  14821. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14822. return false;
  14823. }
  14824. }
  14825. for (index = 0; index < this.meshes.length; index++) {
  14826. var mesh = this.meshes[index];
  14827. if (!mesh.isReady()) {
  14828. return false;
  14829. }
  14830. var mat = mesh.material;
  14831. if (mat) {
  14832. if (!mat.isReady(mesh)) {
  14833. return false;
  14834. }
  14835. }
  14836. }
  14837. return true;
  14838. };
  14839. Scene.prototype.resetCachedMaterial = function () {
  14840. this._cachedMaterial = null;
  14841. };
  14842. Scene.prototype.registerBeforeRender = function (func) {
  14843. this.onBeforeRenderObservable.add(func);
  14844. };
  14845. Scene.prototype.unregisterBeforeRender = function (func) {
  14846. this.onBeforeRenderObservable.removeCallback(func);
  14847. };
  14848. Scene.prototype.registerAfterRender = function (func) {
  14849. this.onAfterRenderObservable.add(func);
  14850. };
  14851. Scene.prototype.unregisterAfterRender = function (func) {
  14852. this.onAfterRenderObservable.removeCallback(func);
  14853. };
  14854. Scene.prototype._addPendingData = function (data) {
  14855. this._pendingData.push(data);
  14856. };
  14857. Scene.prototype._removePendingData = function (data) {
  14858. var index = this._pendingData.indexOf(data);
  14859. if (index !== -1) {
  14860. this._pendingData.splice(index, 1);
  14861. }
  14862. };
  14863. Scene.prototype.getWaitingItemsCount = function () {
  14864. return this._pendingData.length;
  14865. };
  14866. /**
  14867. * Registers a function to be executed when the scene is ready.
  14868. * @param {Function} func - the function to be executed.
  14869. */
  14870. Scene.prototype.executeWhenReady = function (func) {
  14871. var _this = this;
  14872. this.onReadyObservable.add(func);
  14873. if (this._executeWhenReadyTimeoutId !== -1) {
  14874. return;
  14875. }
  14876. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14877. _this._checkIsReady();
  14878. }, 150);
  14879. };
  14880. Scene.prototype._checkIsReady = function () {
  14881. var _this = this;
  14882. if (this.isReady()) {
  14883. this.onReadyObservable.notifyObservers(this);
  14884. this.onReadyObservable.clear();
  14885. this._executeWhenReadyTimeoutId = -1;
  14886. return;
  14887. }
  14888. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14889. _this._checkIsReady();
  14890. }, 150);
  14891. };
  14892. // Animations
  14893. /**
  14894. * Will start the animation sequence of a given target
  14895. * @param target - the target
  14896. * @param {number} from - from which frame should animation start
  14897. * @param {number} to - till which frame should animation run.
  14898. * @param {boolean} [loop] - should the animation loop
  14899. * @param {number} [speedRatio] - the speed in which to run the animation
  14900. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14901. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14902. * @return {BABYLON.Animatable} the animatable object created for this animation
  14903. * @see BABYLON.Animatable
  14904. * @see http://doc.babylonjs.com/page.php?p=22081
  14905. */
  14906. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14907. if (speedRatio === void 0) { speedRatio = 1.0; }
  14908. this.stopAnimation(target);
  14909. if (!animatable) {
  14910. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14911. }
  14912. // Local animations
  14913. if (target.animations) {
  14914. animatable.appendAnimations(target, target.animations);
  14915. }
  14916. // Children animations
  14917. if (target.getAnimatables) {
  14918. var animatables = target.getAnimatables();
  14919. for (var index = 0; index < animatables.length; index++) {
  14920. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14921. }
  14922. }
  14923. animatable.reset();
  14924. return animatable;
  14925. };
  14926. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14927. if (speedRatio === undefined) {
  14928. speedRatio = 1.0;
  14929. }
  14930. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14931. return animatable;
  14932. };
  14933. Scene.prototype.getAnimatableByTarget = function (target) {
  14934. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14935. if (this._activeAnimatables[index].target === target) {
  14936. return this._activeAnimatables[index];
  14937. }
  14938. }
  14939. return null;
  14940. };
  14941. Object.defineProperty(Scene.prototype, "Animatables", {
  14942. get: function () {
  14943. return this._activeAnimatables;
  14944. },
  14945. enumerable: true,
  14946. configurable: true
  14947. });
  14948. /**
  14949. * Will stop the animation of the given target
  14950. * @param target - the target
  14951. * @see beginAnimation
  14952. */
  14953. Scene.prototype.stopAnimation = function (target) {
  14954. var animatable = this.getAnimatableByTarget(target);
  14955. if (animatable) {
  14956. animatable.stop();
  14957. }
  14958. };
  14959. Scene.prototype._animate = function () {
  14960. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14961. return;
  14962. }
  14963. if (!this._animationStartDate) {
  14964. if (this._pendingData.length > 0) {
  14965. return;
  14966. }
  14967. this._animationStartDate = BABYLON.Tools.Now;
  14968. }
  14969. // Getting time
  14970. var now = BABYLON.Tools.Now;
  14971. var delay = now - this._animationStartDate;
  14972. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14973. this._activeAnimatables[index]._animate(delay);
  14974. }
  14975. };
  14976. // Matrix
  14977. Scene.prototype.getViewMatrix = function () {
  14978. return this._viewMatrix;
  14979. };
  14980. Scene.prototype.getProjectionMatrix = function () {
  14981. return this._projectionMatrix;
  14982. };
  14983. Scene.prototype.getTransformMatrix = function () {
  14984. return this._transformMatrix;
  14985. };
  14986. Scene.prototype.setTransformMatrix = function (view, projection) {
  14987. this._viewMatrix = view;
  14988. this._projectionMatrix = projection;
  14989. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14990. };
  14991. // Methods
  14992. Scene.prototype.addMesh = function (newMesh) {
  14993. newMesh.uniqueId = this._uniqueIdCounter++;
  14994. var position = this.meshes.push(newMesh);
  14995. //notify the collision coordinator
  14996. this.collisionCoordinator.onMeshAdded(newMesh);
  14997. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  14998. };
  14999. Scene.prototype.removeMesh = function (toRemove) {
  15000. var index = this.meshes.indexOf(toRemove);
  15001. if (index !== -1) {
  15002. // Remove from the scene if mesh found
  15003. this.meshes.splice(index, 1);
  15004. }
  15005. //notify the collision coordinator
  15006. this.collisionCoordinator.onMeshRemoved(toRemove);
  15007. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15008. return index;
  15009. };
  15010. Scene.prototype.removeSkeleton = function (toRemove) {
  15011. var index = this.skeletons.indexOf(toRemove);
  15012. if (index !== -1) {
  15013. // Remove from the scene if mesh found
  15014. this.skeletons.splice(index, 1);
  15015. }
  15016. return index;
  15017. };
  15018. Scene.prototype.removeLight = function (toRemove) {
  15019. var index = this.lights.indexOf(toRemove);
  15020. if (index !== -1) {
  15021. // Remove from the scene if mesh found
  15022. this.lights.splice(index, 1);
  15023. }
  15024. this.onLightRemovedObservable.notifyObservers(toRemove);
  15025. return index;
  15026. };
  15027. Scene.prototype.removeCamera = function (toRemove) {
  15028. var index = this.cameras.indexOf(toRemove);
  15029. if (index !== -1) {
  15030. // Remove from the scene if mesh found
  15031. this.cameras.splice(index, 1);
  15032. }
  15033. // Remove from activeCameras
  15034. var index2 = this.activeCameras.indexOf(toRemove);
  15035. if (index2 !== -1) {
  15036. // Remove from the scene if mesh found
  15037. this.activeCameras.splice(index2, 1);
  15038. }
  15039. // Reset the activeCamera
  15040. if (this.activeCamera === toRemove) {
  15041. if (this.cameras.length > 0) {
  15042. this.activeCamera = this.cameras[0];
  15043. }
  15044. else {
  15045. this.activeCamera = null;
  15046. }
  15047. }
  15048. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15049. return index;
  15050. };
  15051. Scene.prototype.addLight = function (newLight) {
  15052. newLight.uniqueId = this._uniqueIdCounter++;
  15053. var position = this.lights.push(newLight);
  15054. this.onNewLightAddedObservable.notifyObservers(newLight);
  15055. };
  15056. Scene.prototype.addCamera = function (newCamera) {
  15057. newCamera.uniqueId = this._uniqueIdCounter++;
  15058. var position = this.cameras.push(newCamera);
  15059. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15060. };
  15061. /**
  15062. * Switch active camera
  15063. * @param {Camera} newCamera - new active camera
  15064. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15065. */
  15066. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15067. if (attachControl === void 0) { attachControl = true; }
  15068. var canvas = this._engine.getRenderingCanvas();
  15069. this.activeCamera.detachControl(canvas);
  15070. this.activeCamera = newCamera;
  15071. if (attachControl) {
  15072. newCamera.attachControl(canvas);
  15073. }
  15074. };
  15075. /**
  15076. * sets the active camera of the scene using its ID
  15077. * @param {string} id - the camera's ID
  15078. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15079. * @see activeCamera
  15080. */
  15081. Scene.prototype.setActiveCameraByID = function (id) {
  15082. var camera = this.getCameraByID(id);
  15083. if (camera) {
  15084. this.activeCamera = camera;
  15085. return camera;
  15086. }
  15087. return null;
  15088. };
  15089. /**
  15090. * sets the active camera of the scene using its name
  15091. * @param {string} name - the camera's name
  15092. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15093. * @see activeCamera
  15094. */
  15095. Scene.prototype.setActiveCameraByName = function (name) {
  15096. var camera = this.getCameraByName(name);
  15097. if (camera) {
  15098. this.activeCamera = camera;
  15099. return camera;
  15100. }
  15101. return null;
  15102. };
  15103. /**
  15104. * get a material using its id
  15105. * @param {string} the material's ID
  15106. * @return {BABYLON.Material|null} the material or null if none found.
  15107. */
  15108. Scene.prototype.getMaterialByID = function (id) {
  15109. for (var index = 0; index < this.materials.length; index++) {
  15110. if (this.materials[index].id === id) {
  15111. return this.materials[index];
  15112. }
  15113. }
  15114. return null;
  15115. };
  15116. /**
  15117. * get a material using its name
  15118. * @param {string} the material's name
  15119. * @return {BABYLON.Material|null} the material or null if none found.
  15120. */
  15121. Scene.prototype.getMaterialByName = function (name) {
  15122. for (var index = 0; index < this.materials.length; index++) {
  15123. if (this.materials[index].name === name) {
  15124. return this.materials[index];
  15125. }
  15126. }
  15127. return null;
  15128. };
  15129. Scene.prototype.getLensFlareSystemByName = function (name) {
  15130. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15131. if (this.lensFlareSystems[index].name === name) {
  15132. return this.lensFlareSystems[index];
  15133. }
  15134. }
  15135. return null;
  15136. };
  15137. Scene.prototype.getLensFlareSystemByID = function (id) {
  15138. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15139. if (this.lensFlareSystems[index].id === id) {
  15140. return this.lensFlareSystems[index];
  15141. }
  15142. }
  15143. return null;
  15144. };
  15145. Scene.prototype.getCameraByID = function (id) {
  15146. for (var index = 0; index < this.cameras.length; index++) {
  15147. if (this.cameras[index].id === id) {
  15148. return this.cameras[index];
  15149. }
  15150. }
  15151. return null;
  15152. };
  15153. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15154. for (var index = 0; index < this.cameras.length; index++) {
  15155. if (this.cameras[index].uniqueId === uniqueId) {
  15156. return this.cameras[index];
  15157. }
  15158. }
  15159. return null;
  15160. };
  15161. /**
  15162. * get a camera using its name
  15163. * @param {string} the camera's name
  15164. * @return {BABYLON.Camera|null} the camera or null if none found.
  15165. */
  15166. Scene.prototype.getCameraByName = function (name) {
  15167. for (var index = 0; index < this.cameras.length; index++) {
  15168. if (this.cameras[index].name === name) {
  15169. return this.cameras[index];
  15170. }
  15171. }
  15172. return null;
  15173. };
  15174. /**
  15175. * get a bone using its id
  15176. * @param {string} the bone's id
  15177. * @return {BABYLON.Bone|null} the bone or null if not found
  15178. */
  15179. Scene.prototype.getBoneByID = function (id) {
  15180. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15181. var skeleton = this.skeletons[skeletonIndex];
  15182. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15183. if (skeleton.bones[boneIndex].id === id) {
  15184. return skeleton.bones[boneIndex];
  15185. }
  15186. }
  15187. }
  15188. return null;
  15189. };
  15190. /**
  15191. * get a bone using its id
  15192. * @param {string} the bone's name
  15193. * @return {BABYLON.Bone|null} the bone or null if not found
  15194. */
  15195. Scene.prototype.getBoneByName = function (name) {
  15196. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15197. var skeleton = this.skeletons[skeletonIndex];
  15198. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15199. if (skeleton.bones[boneIndex].name === name) {
  15200. return skeleton.bones[boneIndex];
  15201. }
  15202. }
  15203. }
  15204. return null;
  15205. };
  15206. /**
  15207. * get a light node using its name
  15208. * @param {string} the light's name
  15209. * @return {BABYLON.Light|null} the light or null if none found.
  15210. */
  15211. Scene.prototype.getLightByName = function (name) {
  15212. for (var index = 0; index < this.lights.length; index++) {
  15213. if (this.lights[index].name === name) {
  15214. return this.lights[index];
  15215. }
  15216. }
  15217. return null;
  15218. };
  15219. /**
  15220. * get a light node using its ID
  15221. * @param {string} the light's id
  15222. * @return {BABYLON.Light|null} the light or null if none found.
  15223. */
  15224. Scene.prototype.getLightByID = function (id) {
  15225. for (var index = 0; index < this.lights.length; index++) {
  15226. if (this.lights[index].id === id) {
  15227. return this.lights[index];
  15228. }
  15229. }
  15230. return null;
  15231. };
  15232. /**
  15233. * get a light node using its scene-generated unique ID
  15234. * @param {number} the light's unique id
  15235. * @return {BABYLON.Light|null} the light or null if none found.
  15236. */
  15237. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15238. for (var index = 0; index < this.lights.length; index++) {
  15239. if (this.lights[index].uniqueId === uniqueId) {
  15240. return this.lights[index];
  15241. }
  15242. }
  15243. return null;
  15244. };
  15245. /**
  15246. * get a particle system by id
  15247. * @param id {number} the particle system id
  15248. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15249. */
  15250. Scene.prototype.getParticleSystemByID = function (id) {
  15251. for (var index = 0; index < this.particleSystems.length; index++) {
  15252. if (this.particleSystems[index].id === id) {
  15253. return this.particleSystems[index];
  15254. }
  15255. }
  15256. return null;
  15257. };
  15258. /**
  15259. * get a geometry using its ID
  15260. * @param {string} the geometry's id
  15261. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15262. */
  15263. Scene.prototype.getGeometryByID = function (id) {
  15264. for (var index = 0; index < this._geometries.length; index++) {
  15265. if (this._geometries[index].id === id) {
  15266. return this._geometries[index];
  15267. }
  15268. }
  15269. return null;
  15270. };
  15271. /**
  15272. * add a new geometry to this scene.
  15273. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15274. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15275. * @return {boolean} was the geometry added or not
  15276. */
  15277. Scene.prototype.pushGeometry = function (geometry, force) {
  15278. if (!force && this.getGeometryByID(geometry.id)) {
  15279. return false;
  15280. }
  15281. this._geometries.push(geometry);
  15282. //notify the collision coordinator
  15283. this.collisionCoordinator.onGeometryAdded(geometry);
  15284. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15285. return true;
  15286. };
  15287. /**
  15288. * Removes an existing geometry
  15289. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15290. * @return {boolean} was the geometry removed or not
  15291. */
  15292. Scene.prototype.removeGeometry = function (geometry) {
  15293. var index = this._geometries.indexOf(geometry);
  15294. if (index > -1) {
  15295. this._geometries.splice(index, 1);
  15296. //notify the collision coordinator
  15297. this.collisionCoordinator.onGeometryDeleted(geometry);
  15298. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15299. return true;
  15300. }
  15301. return false;
  15302. };
  15303. Scene.prototype.getGeometries = function () {
  15304. return this._geometries;
  15305. };
  15306. /**
  15307. * Get the first added mesh found of a given ID
  15308. * @param {string} id - the id to search for
  15309. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15310. */
  15311. Scene.prototype.getMeshByID = function (id) {
  15312. for (var index = 0; index < this.meshes.length; index++) {
  15313. if (this.meshes[index].id === id) {
  15314. return this.meshes[index];
  15315. }
  15316. }
  15317. return null;
  15318. };
  15319. Scene.prototype.getMeshesByID = function (id) {
  15320. return this.meshes.filter(function (m) {
  15321. return m.id === id;
  15322. });
  15323. };
  15324. /**
  15325. * Get a mesh with its auto-generated unique id
  15326. * @param {number} uniqueId - the unique id to search for
  15327. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15328. */
  15329. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15330. for (var index = 0; index < this.meshes.length; index++) {
  15331. if (this.meshes[index].uniqueId === uniqueId) {
  15332. return this.meshes[index];
  15333. }
  15334. }
  15335. return null;
  15336. };
  15337. /**
  15338. * Get a the last added mesh found of a given ID
  15339. * @param {string} id - the id to search for
  15340. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15341. */
  15342. Scene.prototype.getLastMeshByID = function (id) {
  15343. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15344. if (this.meshes[index].id === id) {
  15345. return this.meshes[index];
  15346. }
  15347. }
  15348. return null;
  15349. };
  15350. /**
  15351. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15352. * @param {string} id - the id to search for
  15353. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15354. */
  15355. Scene.prototype.getLastEntryByID = function (id) {
  15356. var index;
  15357. for (index = this.meshes.length - 1; index >= 0; index--) {
  15358. if (this.meshes[index].id === id) {
  15359. return this.meshes[index];
  15360. }
  15361. }
  15362. for (index = this.cameras.length - 1; index >= 0; index--) {
  15363. if (this.cameras[index].id === id) {
  15364. return this.cameras[index];
  15365. }
  15366. }
  15367. for (index = this.lights.length - 1; index >= 0; index--) {
  15368. if (this.lights[index].id === id) {
  15369. return this.lights[index];
  15370. }
  15371. }
  15372. return null;
  15373. };
  15374. Scene.prototype.getNodeByID = function (id) {
  15375. var mesh = this.getMeshByID(id);
  15376. if (mesh) {
  15377. return mesh;
  15378. }
  15379. var light = this.getLightByID(id);
  15380. if (light) {
  15381. return light;
  15382. }
  15383. var camera = this.getCameraByID(id);
  15384. if (camera) {
  15385. return camera;
  15386. }
  15387. var bone = this.getBoneByID(id);
  15388. return bone;
  15389. };
  15390. Scene.prototype.getNodeByName = function (name) {
  15391. var mesh = this.getMeshByName(name);
  15392. if (mesh) {
  15393. return mesh;
  15394. }
  15395. var light = this.getLightByName(name);
  15396. if (light) {
  15397. return light;
  15398. }
  15399. var camera = this.getCameraByName(name);
  15400. if (camera) {
  15401. return camera;
  15402. }
  15403. var bone = this.getBoneByName(name);
  15404. return bone;
  15405. };
  15406. Scene.prototype.getMeshByName = function (name) {
  15407. for (var index = 0; index < this.meshes.length; index++) {
  15408. if (this.meshes[index].name === name) {
  15409. return this.meshes[index];
  15410. }
  15411. }
  15412. return null;
  15413. };
  15414. Scene.prototype.getSoundByName = function (name) {
  15415. var index;
  15416. if (BABYLON.AudioEngine) {
  15417. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15418. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15419. return this.mainSoundTrack.soundCollection[index];
  15420. }
  15421. }
  15422. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15423. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15424. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15425. return this.soundTracks[sdIndex].soundCollection[index];
  15426. }
  15427. }
  15428. }
  15429. }
  15430. return null;
  15431. };
  15432. Scene.prototype.getLastSkeletonByID = function (id) {
  15433. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15434. if (this.skeletons[index].id === id) {
  15435. return this.skeletons[index];
  15436. }
  15437. }
  15438. return null;
  15439. };
  15440. Scene.prototype.getSkeletonById = function (id) {
  15441. for (var index = 0; index < this.skeletons.length; index++) {
  15442. if (this.skeletons[index].id === id) {
  15443. return this.skeletons[index];
  15444. }
  15445. }
  15446. return null;
  15447. };
  15448. Scene.prototype.getSkeletonByName = function (name) {
  15449. for (var index = 0; index < this.skeletons.length; index++) {
  15450. if (this.skeletons[index].name === name) {
  15451. return this.skeletons[index];
  15452. }
  15453. }
  15454. return null;
  15455. };
  15456. Scene.prototype.isActiveMesh = function (mesh) {
  15457. return (this._activeMeshes.indexOf(mesh) !== -1);
  15458. };
  15459. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15460. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15461. var material = subMesh.getMaterial();
  15462. if (mesh.showSubMeshesBoundingBox) {
  15463. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15464. }
  15465. if (material) {
  15466. // Render targets
  15467. if (material.getRenderTargetTextures) {
  15468. if (this._processedMaterials.indexOf(material) === -1) {
  15469. this._processedMaterials.push(material);
  15470. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15471. }
  15472. }
  15473. // Dispatch
  15474. this._activeIndices += subMesh.indexCount;
  15475. this._renderingManager.dispatch(subMesh);
  15476. }
  15477. }
  15478. };
  15479. Scene.prototype._isInIntermediateRendering = function () {
  15480. return this._intermediateRendering;
  15481. };
  15482. Scene.prototype._evaluateActiveMeshes = function () {
  15483. this.activeCamera._activeMeshes.reset();
  15484. this._activeMeshes.reset();
  15485. this._renderingManager.reset();
  15486. this._processedMaterials.reset();
  15487. this._activeParticleSystems.reset();
  15488. this._activeSkeletons.reset();
  15489. this._softwareSkinnedMeshes.reset();
  15490. this._boundingBoxRenderer.reset();
  15491. this._edgesRenderers.reset();
  15492. if (!this._frustumPlanes) {
  15493. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15494. }
  15495. else {
  15496. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15497. }
  15498. // Meshes
  15499. var meshes;
  15500. var len;
  15501. if (this._selectionOctree) {
  15502. var selection = this._selectionOctree.select(this._frustumPlanes);
  15503. meshes = selection.data;
  15504. len = selection.length;
  15505. }
  15506. else {
  15507. len = this.meshes.length;
  15508. meshes = this.meshes;
  15509. }
  15510. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15511. var mesh = meshes[meshIndex];
  15512. if (mesh.isBlocked) {
  15513. continue;
  15514. }
  15515. this._totalVertices += mesh.getTotalVertices();
  15516. if (!mesh.isReady() || !mesh.isEnabled()) {
  15517. continue;
  15518. }
  15519. mesh.computeWorldMatrix();
  15520. // Intersections
  15521. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15522. this._meshesForIntersections.pushNoDuplicate(mesh);
  15523. }
  15524. // Switch to current LOD
  15525. var meshLOD = mesh.getLOD(this.activeCamera);
  15526. if (!meshLOD) {
  15527. continue;
  15528. }
  15529. mesh._preActivate();
  15530. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15531. this._activeMeshes.push(mesh);
  15532. this.activeCamera._activeMeshes.push(mesh);
  15533. mesh._activate(this._renderId);
  15534. this._activeMesh(meshLOD);
  15535. }
  15536. }
  15537. // Particle systems
  15538. var beforeParticlesDate = BABYLON.Tools.Now;
  15539. if (this.particlesEnabled) {
  15540. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15541. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15542. var particleSystem = this.particleSystems[particleIndex];
  15543. if (!particleSystem.isStarted()) {
  15544. continue;
  15545. }
  15546. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15547. this._activeParticleSystems.push(particleSystem);
  15548. particleSystem.animate();
  15549. }
  15550. }
  15551. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15552. }
  15553. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15554. };
  15555. Scene.prototype._activeMesh = function (mesh) {
  15556. if (mesh.skeleton && this.skeletonsEnabled) {
  15557. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15558. if (!mesh.computeBonesUsingShaders) {
  15559. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15560. }
  15561. }
  15562. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15563. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15564. }
  15565. if (mesh._edgesRenderer) {
  15566. this._edgesRenderers.push(mesh._edgesRenderer);
  15567. }
  15568. if (mesh && mesh.subMeshes) {
  15569. // Submeshes Octrees
  15570. var len;
  15571. var subMeshes;
  15572. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15573. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15574. len = intersections.length;
  15575. subMeshes = intersections.data;
  15576. }
  15577. else {
  15578. subMeshes = mesh.subMeshes;
  15579. len = subMeshes.length;
  15580. }
  15581. for (var subIndex = 0; subIndex < len; subIndex++) {
  15582. var subMesh = subMeshes[subIndex];
  15583. this._evaluateSubMesh(subMesh, mesh);
  15584. }
  15585. }
  15586. };
  15587. Scene.prototype.updateTransformMatrix = function (force) {
  15588. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15589. };
  15590. Scene.prototype._renderForCamera = function (camera) {
  15591. var engine = this._engine;
  15592. this.activeCamera = camera;
  15593. if (!this.activeCamera)
  15594. throw new Error("Active camera not set");
  15595. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15596. // Viewport
  15597. engine.setViewport(this.activeCamera.viewport);
  15598. // Camera
  15599. this.resetCachedMaterial();
  15600. this._renderId++;
  15601. this.updateTransformMatrix();
  15602. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15603. // Meshes
  15604. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15605. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15606. this._evaluateActiveMeshes();
  15607. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15608. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15609. // Skeletons
  15610. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15611. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15612. skeleton.prepare();
  15613. }
  15614. // Software skinning
  15615. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15616. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15617. mesh.applySkeleton(mesh.skeleton);
  15618. }
  15619. // Render targets
  15620. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15621. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15622. this._intermediateRendering = true;
  15623. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15624. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15625. var renderTarget = this._renderTargets.data[renderIndex];
  15626. if (renderTarget._shouldRender()) {
  15627. this._renderId++;
  15628. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15629. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15630. }
  15631. }
  15632. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15633. this._intermediateRendering = false;
  15634. this._renderId++;
  15635. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15636. }
  15637. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15638. // Prepare Frame
  15639. this.postProcessManager._prepareFrame();
  15640. var beforeRenderDate = BABYLON.Tools.Now;
  15641. // Backgrounds
  15642. var layerIndex;
  15643. var layer;
  15644. if (this.layers.length) {
  15645. engine.setDepthBuffer(false);
  15646. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15647. layer = this.layers[layerIndex];
  15648. if (layer.isBackground) {
  15649. layer.render();
  15650. }
  15651. }
  15652. engine.setDepthBuffer(true);
  15653. }
  15654. // Render
  15655. BABYLON.Tools.StartPerformanceCounter("Main render");
  15656. this._renderingManager.render(null, null, true, true);
  15657. BABYLON.Tools.EndPerformanceCounter("Main render");
  15658. // Bounding boxes
  15659. this._boundingBoxRenderer.render();
  15660. // Edges
  15661. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15662. this._edgesRenderers.data[edgesRendererIndex].render();
  15663. }
  15664. // Lens flares
  15665. if (this.lensFlaresEnabled) {
  15666. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15667. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15668. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15669. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15670. lensFlareSystem.render();
  15671. }
  15672. }
  15673. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15674. }
  15675. // Foregrounds
  15676. if (this.layers.length) {
  15677. engine.setDepthBuffer(false);
  15678. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15679. layer = this.layers[layerIndex];
  15680. if (!layer.isBackground) {
  15681. layer.render();
  15682. }
  15683. }
  15684. engine.setDepthBuffer(true);
  15685. }
  15686. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15687. // Finalize frame
  15688. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15689. // Update camera
  15690. this.activeCamera._updateFromScene();
  15691. // Reset some special arrays
  15692. this._renderTargets.reset();
  15693. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15694. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15695. };
  15696. Scene.prototype._processSubCameras = function (camera) {
  15697. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15698. this._renderForCamera(camera);
  15699. return;
  15700. }
  15701. // rig cameras
  15702. for (var index = 0; index < camera._rigCameras.length; index++) {
  15703. this._renderForCamera(camera._rigCameras[index]);
  15704. }
  15705. this.activeCamera = camera;
  15706. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15707. // Update camera
  15708. this.activeCamera._updateFromScene();
  15709. };
  15710. Scene.prototype._checkIntersections = function () {
  15711. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15712. var sourceMesh = this._meshesForIntersections.data[index];
  15713. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15714. var action = sourceMesh.actionManager.actions[actionIndex];
  15715. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15716. var parameters = action.getTriggerParameter();
  15717. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15718. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15719. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15720. if (areIntersecting && currentIntersectionInProgress === -1) {
  15721. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15722. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15723. sourceMesh._intersectionsInProgress.push(otherMesh);
  15724. }
  15725. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15726. sourceMesh._intersectionsInProgress.push(otherMesh);
  15727. }
  15728. }
  15729. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15730. //They intersected, and now they don't.
  15731. //is this trigger an exit trigger? execute an event.
  15732. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15733. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15734. }
  15735. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15736. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15737. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15738. }
  15739. }
  15740. }
  15741. }
  15742. }
  15743. };
  15744. Scene.prototype.render = function () {
  15745. var startDate = BABYLON.Tools.Now;
  15746. this._particlesDuration = 0;
  15747. this._spritesDuration = 0;
  15748. this._activeParticles = 0;
  15749. this._renderDuration = 0;
  15750. this._renderTargetsDuration = 0;
  15751. this._evaluateActiveMeshesDuration = 0;
  15752. this._totalVertices = 0;
  15753. this._activeIndices = 0;
  15754. this._activeBones = 0;
  15755. this.getEngine().resetDrawCalls();
  15756. this._meshesForIntersections.reset();
  15757. this.resetCachedMaterial();
  15758. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15759. // Actions
  15760. if (this.actionManager) {
  15761. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15762. }
  15763. //Simplification Queue
  15764. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15765. this.simplificationQueue.executeNext();
  15766. }
  15767. // Animations
  15768. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15769. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15770. this._animate();
  15771. // Physics
  15772. if (this._physicsEngine) {
  15773. BABYLON.Tools.StartPerformanceCounter("Physics");
  15774. this._physicsEngine._step(deltaTime / 1000.0);
  15775. BABYLON.Tools.EndPerformanceCounter("Physics");
  15776. }
  15777. // Before render
  15778. this.onBeforeRenderObservable.notifyObservers(this);
  15779. // Customs render targets
  15780. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15781. var engine = this.getEngine();
  15782. var currentActiveCamera = this.activeCamera;
  15783. if (this.renderTargetsEnabled) {
  15784. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15785. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15786. var renderTarget = this.customRenderTargets[customIndex];
  15787. if (renderTarget._shouldRender()) {
  15788. this._renderId++;
  15789. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15790. if (!this.activeCamera)
  15791. throw new Error("Active camera not set");
  15792. // Viewport
  15793. engine.setViewport(this.activeCamera.viewport);
  15794. // Camera
  15795. this.updateTransformMatrix();
  15796. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15797. }
  15798. }
  15799. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15800. this._renderId++;
  15801. }
  15802. if (this.customRenderTargets.length > 0) {
  15803. engine.restoreDefaultFramebuffer();
  15804. }
  15805. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15806. this.activeCamera = currentActiveCamera;
  15807. // Procedural textures
  15808. if (this.proceduralTexturesEnabled) {
  15809. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15810. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15811. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15812. if (proceduralTexture._shouldRender()) {
  15813. proceduralTexture.render();
  15814. }
  15815. }
  15816. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15817. }
  15818. // Clear
  15819. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15820. // Shadows
  15821. if (this.shadowsEnabled) {
  15822. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15823. var light = this.lights[lightIndex];
  15824. var shadowGenerator = light.getShadowGenerator();
  15825. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15826. this._renderTargets.push(shadowGenerator.getShadowMap());
  15827. }
  15828. }
  15829. }
  15830. // Depth renderer
  15831. if (this._depthRenderer) {
  15832. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15833. }
  15834. // RenderPipeline
  15835. this.postProcessRenderPipelineManager.update();
  15836. // Multi-cameras?
  15837. if (this.activeCameras.length > 0) {
  15838. var currentRenderId = this._renderId;
  15839. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15840. this._renderId = currentRenderId;
  15841. if (cameraIndex > 0) {
  15842. this._engine.clear(0, false, true);
  15843. }
  15844. this._processSubCameras(this.activeCameras[cameraIndex]);
  15845. }
  15846. }
  15847. else {
  15848. if (!this.activeCamera) {
  15849. throw new Error("No camera defined");
  15850. }
  15851. this._processSubCameras(this.activeCamera);
  15852. }
  15853. // Intersection checks
  15854. this._checkIntersections();
  15855. // Update the audio listener attached to the camera
  15856. if (BABYLON.AudioEngine) {
  15857. this._updateAudioParameters();
  15858. }
  15859. // After render
  15860. if (this.afterRender) {
  15861. this.afterRender();
  15862. }
  15863. this.onAfterRenderObservable.notifyObservers(this);
  15864. // Cleaning
  15865. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15866. this._toBeDisposed.data[index].dispose();
  15867. this._toBeDisposed[index] = null;
  15868. }
  15869. this._toBeDisposed.reset();
  15870. if (this.dumpNextRenderTargets) {
  15871. this.dumpNextRenderTargets = false;
  15872. }
  15873. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15874. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15875. };
  15876. Scene.prototype._updateAudioParameters = function () {
  15877. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15878. return;
  15879. }
  15880. var listeningCamera;
  15881. var audioEngine = BABYLON.Engine.audioEngine;
  15882. if (this.activeCameras.length > 0) {
  15883. listeningCamera = this.activeCameras[0];
  15884. }
  15885. else {
  15886. listeningCamera = this.activeCamera;
  15887. }
  15888. if (listeningCamera && audioEngine.canUseWebAudio) {
  15889. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15890. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15891. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15892. cameraDirection.normalize();
  15893. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15894. var i;
  15895. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15896. var sound = this.mainSoundTrack.soundCollection[i];
  15897. if (sound.useCustomAttenuation) {
  15898. sound.updateDistanceFromListener();
  15899. }
  15900. }
  15901. for (i = 0; i < this.soundTracks.length; i++) {
  15902. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15903. sound = this.soundTracks[i].soundCollection[j];
  15904. if (sound.useCustomAttenuation) {
  15905. sound.updateDistanceFromListener();
  15906. }
  15907. }
  15908. }
  15909. }
  15910. };
  15911. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15912. // Audio
  15913. get: function () {
  15914. return this._audioEnabled;
  15915. },
  15916. set: function (value) {
  15917. this._audioEnabled = value;
  15918. if (BABYLON.AudioEngine) {
  15919. if (this._audioEnabled) {
  15920. this._enableAudio();
  15921. }
  15922. else {
  15923. this._disableAudio();
  15924. }
  15925. }
  15926. },
  15927. enumerable: true,
  15928. configurable: true
  15929. });
  15930. Scene.prototype._disableAudio = function () {
  15931. var i;
  15932. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15933. this.mainSoundTrack.soundCollection[i].pause();
  15934. }
  15935. for (i = 0; i < this.soundTracks.length; i++) {
  15936. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15937. this.soundTracks[i].soundCollection[j].pause();
  15938. }
  15939. }
  15940. };
  15941. Scene.prototype._enableAudio = function () {
  15942. var i;
  15943. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15944. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15945. this.mainSoundTrack.soundCollection[i].play();
  15946. }
  15947. }
  15948. for (i = 0; i < this.soundTracks.length; i++) {
  15949. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15950. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15951. this.soundTracks[i].soundCollection[j].play();
  15952. }
  15953. }
  15954. }
  15955. };
  15956. Object.defineProperty(Scene.prototype, "headphone", {
  15957. get: function () {
  15958. return this._headphone;
  15959. },
  15960. set: function (value) {
  15961. this._headphone = value;
  15962. if (BABYLON.AudioEngine) {
  15963. if (this._headphone) {
  15964. this._switchAudioModeForHeadphones();
  15965. }
  15966. else {
  15967. this._switchAudioModeForNormalSpeakers();
  15968. }
  15969. }
  15970. },
  15971. enumerable: true,
  15972. configurable: true
  15973. });
  15974. Scene.prototype._switchAudioModeForHeadphones = function () {
  15975. this.mainSoundTrack.switchPanningModelToHRTF();
  15976. for (var i = 0; i < this.soundTracks.length; i++) {
  15977. this.soundTracks[i].switchPanningModelToHRTF();
  15978. }
  15979. };
  15980. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15981. this.mainSoundTrack.switchPanningModelToEqualPower();
  15982. for (var i = 0; i < this.soundTracks.length; i++) {
  15983. this.soundTracks[i].switchPanningModelToEqualPower();
  15984. }
  15985. };
  15986. Scene.prototype.enableDepthRenderer = function () {
  15987. if (this._depthRenderer) {
  15988. return this._depthRenderer;
  15989. }
  15990. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15991. return this._depthRenderer;
  15992. };
  15993. Scene.prototype.disableDepthRenderer = function () {
  15994. if (!this._depthRenderer) {
  15995. return;
  15996. }
  15997. this._depthRenderer.dispose();
  15998. this._depthRenderer = null;
  15999. };
  16000. Scene.prototype.freezeMaterials = function () {
  16001. for (var i = 0; i < this.materials.length; i++) {
  16002. this.materials[i].freeze();
  16003. }
  16004. };
  16005. Scene.prototype.unfreezeMaterials = function () {
  16006. for (var i = 0; i < this.materials.length; i++) {
  16007. this.materials[i].unfreeze();
  16008. }
  16009. };
  16010. Scene.prototype.dispose = function () {
  16011. this.beforeRender = null;
  16012. this.afterRender = null;
  16013. this.skeletons = [];
  16014. this._boundingBoxRenderer.dispose();
  16015. if (this._depthRenderer) {
  16016. this._depthRenderer.dispose();
  16017. }
  16018. // Debug layer
  16019. this.debugLayer.hide();
  16020. // Events
  16021. if (this.onDispose) {
  16022. this.onDispose();
  16023. }
  16024. this.onBeforeRenderObservable.clear();
  16025. this.onAfterRenderObservable.clear();
  16026. this.detachControl();
  16027. // Release sounds & sounds tracks
  16028. if (BABYLON.AudioEngine) {
  16029. this.disposeSounds();
  16030. }
  16031. // Detach cameras
  16032. var canvas = this._engine.getRenderingCanvas();
  16033. var index;
  16034. for (index = 0; index < this.cameras.length; index++) {
  16035. this.cameras[index].detachControl(canvas);
  16036. }
  16037. // Release lights
  16038. while (this.lights.length) {
  16039. this.lights[0].dispose();
  16040. }
  16041. // Release meshes
  16042. while (this.meshes.length) {
  16043. this.meshes[0].dispose(true);
  16044. }
  16045. // Release cameras
  16046. while (this.cameras.length) {
  16047. this.cameras[0].dispose();
  16048. }
  16049. // Release materials
  16050. while (this.materials.length) {
  16051. this.materials[0].dispose();
  16052. }
  16053. // Release particles
  16054. while (this.particleSystems.length) {
  16055. this.particleSystems[0].dispose();
  16056. }
  16057. // Release sprites
  16058. while (this.spriteManagers.length) {
  16059. this.spriteManagers[0].dispose();
  16060. }
  16061. // Release layers
  16062. while (this.layers.length) {
  16063. this.layers[0].dispose();
  16064. }
  16065. // Release textures
  16066. while (this.textures.length) {
  16067. this.textures[0].dispose();
  16068. }
  16069. // Post-processes
  16070. this.postProcessManager.dispose();
  16071. // Physics
  16072. if (this._physicsEngine) {
  16073. this.disablePhysicsEngine();
  16074. }
  16075. // Remove from engine
  16076. index = this._engine.scenes.indexOf(this);
  16077. if (index > -1) {
  16078. this._engine.scenes.splice(index, 1);
  16079. }
  16080. this._engine.wipeCaches();
  16081. };
  16082. // Release sounds & sounds tracks
  16083. Scene.prototype.disposeSounds = function () {
  16084. this.mainSoundTrack.dispose();
  16085. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16086. this.soundTracks[scIndex].dispose();
  16087. }
  16088. };
  16089. // Octrees
  16090. Scene.prototype.getWorldExtends = function () {
  16091. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16092. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16093. for (var index = 0; index < this.meshes.length; index++) {
  16094. var mesh = this.meshes[index];
  16095. mesh.computeWorldMatrix(true);
  16096. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16097. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16098. BABYLON.Tools.CheckExtends(minBox, min, max);
  16099. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16100. }
  16101. return {
  16102. min: min,
  16103. max: max
  16104. };
  16105. };
  16106. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16107. if (maxCapacity === void 0) { maxCapacity = 64; }
  16108. if (maxDepth === void 0) { maxDepth = 2; }
  16109. if (!this._selectionOctree) {
  16110. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16111. }
  16112. var worldExtends = this.getWorldExtends();
  16113. // Update octree
  16114. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16115. return this._selectionOctree;
  16116. };
  16117. // Picking
  16118. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16119. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16120. var engine = this._engine;
  16121. if (!camera) {
  16122. if (!this.activeCamera)
  16123. throw new Error("Active camera not set");
  16124. camera = this.activeCamera;
  16125. }
  16126. var cameraViewport = camera.viewport;
  16127. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16128. // Moving coordinates to local viewport world
  16129. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16130. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16131. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16132. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16133. };
  16134. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16135. var engine = this._engine;
  16136. if (!camera) {
  16137. if (!this.activeCamera)
  16138. throw new Error("Active camera not set");
  16139. camera = this.activeCamera;
  16140. }
  16141. var cameraViewport = camera.viewport;
  16142. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16143. var identity = BABYLON.Matrix.Identity();
  16144. // Moving coordinates to local viewport world
  16145. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16146. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16147. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16148. };
  16149. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16150. var pickingInfo = null;
  16151. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16152. var mesh = this.meshes[meshIndex];
  16153. if (predicate) {
  16154. if (!predicate(mesh)) {
  16155. continue;
  16156. }
  16157. }
  16158. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16159. continue;
  16160. }
  16161. var world = mesh.getWorldMatrix();
  16162. var ray = rayFunction(world);
  16163. var result = mesh.intersects(ray, fastCheck);
  16164. if (!result || !result.hit)
  16165. continue;
  16166. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16167. continue;
  16168. pickingInfo = result;
  16169. if (fastCheck) {
  16170. break;
  16171. }
  16172. }
  16173. return pickingInfo || new BABYLON.PickingInfo();
  16174. };
  16175. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16176. var pickingInfo = null;
  16177. camera = camera || this.activeCamera;
  16178. if (this.spriteManagers.length > 0) {
  16179. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16180. var spriteManager = this.spriteManagers[spriteIndex];
  16181. if (!spriteManager.isPickable) {
  16182. continue;
  16183. }
  16184. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16185. if (!result || !result.hit)
  16186. continue;
  16187. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16188. continue;
  16189. pickingInfo = result;
  16190. if (fastCheck) {
  16191. break;
  16192. }
  16193. }
  16194. }
  16195. return pickingInfo || new BABYLON.PickingInfo();
  16196. };
  16197. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16198. var _this = this;
  16199. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16200. /// <param name="x">X position on screen</param>
  16201. /// <param name="y">Y position on screen</param>
  16202. /// <param name="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</param>
  16203. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16204. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  16205. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16206. };
  16207. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16208. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16209. /// <param name="x">X position on screen</param>
  16210. /// <param name="y">Y position on screen</param>
  16211. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  16212. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16213. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  16214. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16215. };
  16216. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16217. var _this = this;
  16218. return this._internalPick(function (world) {
  16219. if (!_this._pickWithRayInverseMatrix) {
  16220. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16221. }
  16222. world.invertToRef(_this._pickWithRayInverseMatrix);
  16223. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16224. }, predicate, fastCheck);
  16225. };
  16226. Scene.prototype.setPointerOverMesh = function (mesh) {
  16227. if (this._pointerOverMesh === mesh) {
  16228. return;
  16229. }
  16230. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16231. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16232. }
  16233. this._pointerOverMesh = mesh;
  16234. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16235. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16236. }
  16237. };
  16238. Scene.prototype.getPointerOverMesh = function () {
  16239. return this._pointerOverMesh;
  16240. };
  16241. Scene.prototype.setPointerOverSprite = function (sprite) {
  16242. if (this._pointerOverSprite === sprite) {
  16243. return;
  16244. }
  16245. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16246. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16247. }
  16248. this._pointerOverSprite = sprite;
  16249. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16250. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16251. }
  16252. };
  16253. Scene.prototype.getPointerOverSprite = function () {
  16254. return this._pointerOverSprite;
  16255. };
  16256. // Physics
  16257. Scene.prototype.getPhysicsEngine = function () {
  16258. return this._physicsEngine;
  16259. };
  16260. /**
  16261. * Enables physics to the current scene
  16262. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16263. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16264. * @return {boolean} was the physics engine initialized
  16265. */
  16266. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16267. if (this._physicsEngine) {
  16268. return true;
  16269. }
  16270. try {
  16271. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16272. return true;
  16273. }
  16274. catch (e) {
  16275. BABYLON.Tools.Error(e.message);
  16276. return false;
  16277. }
  16278. };
  16279. Scene.prototype.disablePhysicsEngine = function () {
  16280. if (!this._physicsEngine) {
  16281. return;
  16282. }
  16283. this._physicsEngine.dispose();
  16284. this._physicsEngine = undefined;
  16285. };
  16286. Scene.prototype.isPhysicsEnabled = function () {
  16287. return this._physicsEngine !== undefined;
  16288. };
  16289. /**
  16290. *
  16291. * Sets the gravity of the physics engine (and NOT of the scene)
  16292. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16293. */
  16294. Scene.prototype.setGravity = function (gravity) {
  16295. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16296. if (!this._physicsEngine) {
  16297. return;
  16298. }
  16299. this._physicsEngine.setGravity(gravity);
  16300. };
  16301. /**
  16302. * Legacy support, using the new API
  16303. * @Deprecated
  16304. */
  16305. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16306. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16307. if (parts.parts) {
  16308. options = parts;
  16309. parts = parts.parts;
  16310. }
  16311. var mainMesh = parts[0].mesh;
  16312. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16313. for (var index = 1; index < parts.length; index++) {
  16314. var mesh = parts[index].mesh;
  16315. if (mesh.parent !== mainMesh) {
  16316. mesh.position = mesh.position.subtract(mainMesh.position);
  16317. mesh.parent = mainMesh;
  16318. }
  16319. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16320. }
  16321. mainMesh.physicsImpostor.forceUpdate();
  16322. };
  16323. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16324. var mesh = compound.parts[0].mesh;
  16325. mesh.physicsImpostor.dispose();
  16326. mesh.physicsImpostor = null;
  16327. };
  16328. // Misc.
  16329. Scene.prototype.createDefaultCameraOrLight = function () {
  16330. // Light
  16331. if (this.lights.length === 0) {
  16332. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16333. }
  16334. // Camera
  16335. if (!this.activeCamera) {
  16336. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16337. // Compute position
  16338. var worldExtends = this.getWorldExtends();
  16339. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16340. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16341. camera.setTarget(worldCenter);
  16342. this.activeCamera = camera;
  16343. }
  16344. };
  16345. // Tags
  16346. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16347. if (tagsQuery === undefined) {
  16348. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16349. return list;
  16350. }
  16351. var listByTags = [];
  16352. forEach = forEach || (function (item) { return; });
  16353. for (var i in list) {
  16354. var item = list[i];
  16355. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16356. listByTags.push(item);
  16357. forEach(item);
  16358. }
  16359. }
  16360. return listByTags;
  16361. };
  16362. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16363. return this._getByTags(this.meshes, tagsQuery, forEach);
  16364. };
  16365. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16366. return this._getByTags(this.cameras, tagsQuery, forEach);
  16367. };
  16368. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16369. return this._getByTags(this.lights, tagsQuery, forEach);
  16370. };
  16371. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16372. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16373. };
  16374. // Statics
  16375. Scene._FOGMODE_NONE = 0;
  16376. Scene._FOGMODE_EXP = 1;
  16377. Scene._FOGMODE_EXP2 = 2;
  16378. Scene._FOGMODE_LINEAR = 3;
  16379. Scene.MinDeltaTime = 1.0;
  16380. Scene.MaxDeltaTime = 1000.0;
  16381. return Scene;
  16382. })();
  16383. BABYLON.Scene = Scene;
  16384. })(BABYLON || (BABYLON = {}));
  16385. var BABYLON;
  16386. (function (BABYLON) {
  16387. var VertexBuffer = (function () {
  16388. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16389. if (engine instanceof BABYLON.Mesh) {
  16390. this._engine = engine.getScene().getEngine();
  16391. }
  16392. else {
  16393. this._engine = engine;
  16394. }
  16395. this._updatable = updatable;
  16396. this._data = data;
  16397. if (!postponeInternalCreation) {
  16398. this.create();
  16399. }
  16400. this._kind = kind;
  16401. if (stride) {
  16402. this._strideSize = stride;
  16403. return;
  16404. }
  16405. // Deduce stride from kind
  16406. switch (kind) {
  16407. case VertexBuffer.PositionKind:
  16408. this._strideSize = 3;
  16409. break;
  16410. case VertexBuffer.NormalKind:
  16411. this._strideSize = 3;
  16412. break;
  16413. case VertexBuffer.UVKind:
  16414. case VertexBuffer.UV2Kind:
  16415. case VertexBuffer.UV3Kind:
  16416. case VertexBuffer.UV4Kind:
  16417. case VertexBuffer.UV5Kind:
  16418. case VertexBuffer.UV6Kind:
  16419. this._strideSize = 2;
  16420. break;
  16421. case VertexBuffer.ColorKind:
  16422. this._strideSize = 4;
  16423. break;
  16424. case VertexBuffer.MatricesIndicesKind:
  16425. case VertexBuffer.MatricesIndicesExtraKind:
  16426. this._strideSize = 4;
  16427. break;
  16428. case VertexBuffer.MatricesWeightsKind:
  16429. case VertexBuffer.MatricesWeightsExtraKind:
  16430. this._strideSize = 4;
  16431. break;
  16432. }
  16433. }
  16434. // Properties
  16435. VertexBuffer.prototype.isUpdatable = function () {
  16436. return this._updatable;
  16437. };
  16438. VertexBuffer.prototype.getData = function () {
  16439. return this._data;
  16440. };
  16441. VertexBuffer.prototype.getBuffer = function () {
  16442. return this._buffer;
  16443. };
  16444. VertexBuffer.prototype.getStrideSize = function () {
  16445. return this._strideSize;
  16446. };
  16447. // Methods
  16448. VertexBuffer.prototype.create = function (data) {
  16449. if (!data && this._buffer) {
  16450. return; // nothing to do
  16451. }
  16452. data = data || this._data;
  16453. if (!this._buffer) {
  16454. if (this._updatable) {
  16455. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16456. }
  16457. else {
  16458. this._buffer = this._engine.createVertexBuffer(data);
  16459. }
  16460. }
  16461. if (this._updatable) {
  16462. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16463. this._data = data;
  16464. }
  16465. };
  16466. VertexBuffer.prototype.update = function (data) {
  16467. this.create(data);
  16468. };
  16469. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16470. if (!this._buffer) {
  16471. return;
  16472. }
  16473. if (this._updatable) {
  16474. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16475. this._data = null;
  16476. }
  16477. };
  16478. VertexBuffer.prototype.dispose = function () {
  16479. if (!this._buffer) {
  16480. return;
  16481. }
  16482. if (this._engine._releaseBuffer(this._buffer)) {
  16483. this._buffer = null;
  16484. }
  16485. };
  16486. Object.defineProperty(VertexBuffer, "PositionKind", {
  16487. get: function () {
  16488. return VertexBuffer._PositionKind;
  16489. },
  16490. enumerable: true,
  16491. configurable: true
  16492. });
  16493. Object.defineProperty(VertexBuffer, "NormalKind", {
  16494. get: function () {
  16495. return VertexBuffer._NormalKind;
  16496. },
  16497. enumerable: true,
  16498. configurable: true
  16499. });
  16500. Object.defineProperty(VertexBuffer, "UVKind", {
  16501. get: function () {
  16502. return VertexBuffer._UVKind;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16508. get: function () {
  16509. return VertexBuffer._UV2Kind;
  16510. },
  16511. enumerable: true,
  16512. configurable: true
  16513. });
  16514. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16515. get: function () {
  16516. return VertexBuffer._UV3Kind;
  16517. },
  16518. enumerable: true,
  16519. configurable: true
  16520. });
  16521. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16522. get: function () {
  16523. return VertexBuffer._UV4Kind;
  16524. },
  16525. enumerable: true,
  16526. configurable: true
  16527. });
  16528. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16529. get: function () {
  16530. return VertexBuffer._UV5Kind;
  16531. },
  16532. enumerable: true,
  16533. configurable: true
  16534. });
  16535. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16536. get: function () {
  16537. return VertexBuffer._UV6Kind;
  16538. },
  16539. enumerable: true,
  16540. configurable: true
  16541. });
  16542. Object.defineProperty(VertexBuffer, "ColorKind", {
  16543. get: function () {
  16544. return VertexBuffer._ColorKind;
  16545. },
  16546. enumerable: true,
  16547. configurable: true
  16548. });
  16549. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16550. get: function () {
  16551. return VertexBuffer._MatricesIndicesKind;
  16552. },
  16553. enumerable: true,
  16554. configurable: true
  16555. });
  16556. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16557. get: function () {
  16558. return VertexBuffer._MatricesWeightsKind;
  16559. },
  16560. enumerable: true,
  16561. configurable: true
  16562. });
  16563. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16564. get: function () {
  16565. return VertexBuffer._MatricesIndicesExtraKind;
  16566. },
  16567. enumerable: true,
  16568. configurable: true
  16569. });
  16570. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16571. get: function () {
  16572. return VertexBuffer._MatricesWeightsExtraKind;
  16573. },
  16574. enumerable: true,
  16575. configurable: true
  16576. });
  16577. // Enums
  16578. VertexBuffer._PositionKind = "position";
  16579. VertexBuffer._NormalKind = "normal";
  16580. VertexBuffer._UVKind = "uv";
  16581. VertexBuffer._UV2Kind = "uv2";
  16582. VertexBuffer._UV3Kind = "uv3";
  16583. VertexBuffer._UV4Kind = "uv4";
  16584. VertexBuffer._UV5Kind = "uv5";
  16585. VertexBuffer._UV6Kind = "uv6";
  16586. VertexBuffer._ColorKind = "color";
  16587. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16588. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16589. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16590. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16591. return VertexBuffer;
  16592. })();
  16593. BABYLON.VertexBuffer = VertexBuffer;
  16594. })(BABYLON || (BABYLON = {}));
  16595. var BABYLON;
  16596. (function (BABYLON) {
  16597. /**
  16598. * Creates an instance based on a source mesh.
  16599. */
  16600. var InstancedMesh = (function (_super) {
  16601. __extends(InstancedMesh, _super);
  16602. function InstancedMesh(name, source) {
  16603. _super.call(this, name, source.getScene());
  16604. source.instances.push(this);
  16605. this._sourceMesh = source;
  16606. this.position.copyFrom(source.position);
  16607. this.rotation.copyFrom(source.rotation);
  16608. this.scaling.copyFrom(source.scaling);
  16609. if (source.rotationQuaternion) {
  16610. this.rotationQuaternion = source.rotationQuaternion.clone();
  16611. }
  16612. this.infiniteDistance = source.infiniteDistance;
  16613. this.setPivotMatrix(source.getPivotMatrix());
  16614. this.refreshBoundingInfo();
  16615. this._syncSubMeshes();
  16616. }
  16617. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16618. // Methods
  16619. get: function () {
  16620. return this._sourceMesh.receiveShadows;
  16621. },
  16622. enumerable: true,
  16623. configurable: true
  16624. });
  16625. Object.defineProperty(InstancedMesh.prototype, "material", {
  16626. get: function () {
  16627. return this._sourceMesh.material;
  16628. },
  16629. enumerable: true,
  16630. configurable: true
  16631. });
  16632. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16633. get: function () {
  16634. return this._sourceMesh.visibility;
  16635. },
  16636. enumerable: true,
  16637. configurable: true
  16638. });
  16639. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16640. get: function () {
  16641. return this._sourceMesh.skeleton;
  16642. },
  16643. enumerable: true,
  16644. configurable: true
  16645. });
  16646. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16647. get: function () {
  16648. return this._sourceMesh.renderingGroupId;
  16649. },
  16650. enumerable: true,
  16651. configurable: true
  16652. });
  16653. InstancedMesh.prototype.getTotalVertices = function () {
  16654. return this._sourceMesh.getTotalVertices();
  16655. };
  16656. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16657. get: function () {
  16658. return this._sourceMesh;
  16659. },
  16660. enumerable: true,
  16661. configurable: true
  16662. });
  16663. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16664. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16665. };
  16666. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16667. return this._sourceMesh.isVerticesDataPresent(kind);
  16668. };
  16669. InstancedMesh.prototype.getIndices = function () {
  16670. return this._sourceMesh.getIndices();
  16671. };
  16672. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16673. get: function () {
  16674. return this._sourceMesh._positions;
  16675. },
  16676. enumerable: true,
  16677. configurable: true
  16678. });
  16679. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16680. var meshBB = this._sourceMesh.getBoundingInfo();
  16681. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16682. this._updateBoundingInfo();
  16683. };
  16684. InstancedMesh.prototype._preActivate = function () {
  16685. if (this._currentLOD) {
  16686. this._currentLOD._preActivate();
  16687. }
  16688. };
  16689. InstancedMesh.prototype._activate = function (renderId) {
  16690. if (this._currentLOD) {
  16691. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16692. }
  16693. };
  16694. InstancedMesh.prototype.getLOD = function (camera) {
  16695. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16696. if (this._currentLOD === this.sourceMesh) {
  16697. return this;
  16698. }
  16699. return this._currentLOD;
  16700. };
  16701. InstancedMesh.prototype._syncSubMeshes = function () {
  16702. this.releaseSubMeshes();
  16703. if (this._sourceMesh.subMeshes) {
  16704. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16705. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16706. }
  16707. }
  16708. };
  16709. InstancedMesh.prototype._generatePointsArray = function () {
  16710. return this._sourceMesh._generatePointsArray();
  16711. };
  16712. // Clone
  16713. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16714. var result = this._sourceMesh.createInstance(name);
  16715. // Deep copy
  16716. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  16717. // Bounding info
  16718. this.refreshBoundingInfo();
  16719. // Parent
  16720. if (newParent) {
  16721. result.parent = newParent;
  16722. }
  16723. if (!doNotCloneChildren) {
  16724. // Children
  16725. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16726. var mesh = this.getScene().meshes[index];
  16727. if (mesh.parent === this) {
  16728. mesh.clone(mesh.name, result);
  16729. }
  16730. }
  16731. }
  16732. result.computeWorldMatrix(true);
  16733. return result;
  16734. };
  16735. // Dispoe
  16736. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16737. // Remove from mesh
  16738. var index = this._sourceMesh.instances.indexOf(this);
  16739. this._sourceMesh.instances.splice(index, 1);
  16740. _super.prototype.dispose.call(this, doNotRecurse);
  16741. };
  16742. return InstancedMesh;
  16743. })(BABYLON.AbstractMesh);
  16744. BABYLON.InstancedMesh = InstancedMesh;
  16745. })(BABYLON || (BABYLON = {}));
  16746. var BABYLON;
  16747. (function (BABYLON) {
  16748. var _InstancesBatch = (function () {
  16749. function _InstancesBatch() {
  16750. this.mustReturn = false;
  16751. this.visibleInstances = new Array();
  16752. this.renderSelf = new Array();
  16753. }
  16754. return _InstancesBatch;
  16755. })();
  16756. BABYLON._InstancesBatch = _InstancesBatch;
  16757. var Mesh = (function (_super) {
  16758. __extends(Mesh, _super);
  16759. /**
  16760. * @constructor
  16761. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16762. * @param {Scene} scene - The scene to add this mesh to.
  16763. * @param {Node} parent - The parent of this mesh, if it has one
  16764. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16765. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16766. * When false, achieved by calling a clone(), also passing False.
  16767. * This will make creation of children, recursive.
  16768. */
  16769. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  16770. if (parent === void 0) { parent = null; }
  16771. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  16772. _super.call(this, name, scene);
  16773. // Events
  16774. /**
  16775. * An event triggered before rendering the mesh
  16776. * @type {BABYLON.Observable}
  16777. */
  16778. this.onBeforeRenderObservable = new BABYLON.Observable();
  16779. /**
  16780. * An event triggered after rendering the mesh
  16781. * @type {BABYLON.Observable}
  16782. */
  16783. this.onAfterRenderObservable = new BABYLON.Observable();
  16784. /**
  16785. * An event triggered before drawing the mesh
  16786. * @type {BABYLON.Observable}
  16787. */
  16788. this.onBeforeDrawObservable = new BABYLON.Observable();
  16789. // Members
  16790. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16791. this.instances = new Array();
  16792. this._LODLevels = new Array();
  16793. this._visibleInstances = {};
  16794. this._renderIdForInstances = new Array();
  16795. this._batchCache = new _InstancesBatch();
  16796. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16797. this._sideOrientation = Mesh._DEFAULTSIDE;
  16798. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16799. if (source) {
  16800. // Geometry
  16801. if (source._geometry) {
  16802. source._geometry.applyToMesh(this);
  16803. }
  16804. // Deep copy
  16805. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16806. // Pivot
  16807. this.setPivotMatrix(source.getPivotMatrix());
  16808. this.id = name + "." + source.id;
  16809. // Material
  16810. this.material = source.material;
  16811. var index;
  16812. if (!doNotCloneChildren) {
  16813. // Children
  16814. for (index = 0; index < scene.meshes.length; index++) {
  16815. var mesh = scene.meshes[index];
  16816. if (mesh.parent === source) {
  16817. // doNotCloneChildren is always going to be False
  16818. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16819. }
  16820. }
  16821. }
  16822. // Physics clone
  16823. var physicsEngine = this.getScene().getPhysicsEngine();
  16824. if (clonePhysicsImpostor && physicsEngine) {
  16825. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  16826. if (impostor) {
  16827. this.physicsImpostor = impostor.clone(this);
  16828. }
  16829. }
  16830. // Particles
  16831. for (index = 0; index < scene.particleSystems.length; index++) {
  16832. var system = scene.particleSystems[index];
  16833. if (system.emitter === source) {
  16834. system.clone(system.name, this);
  16835. }
  16836. }
  16837. this.computeWorldMatrix(true);
  16838. }
  16839. // Parent
  16840. if (parent !== null) {
  16841. this.parent = parent;
  16842. }
  16843. }
  16844. Object.defineProperty(Mesh, "FRONTSIDE", {
  16845. /**
  16846. * Mesh side orientation : usually the external or front surface
  16847. */
  16848. get: function () {
  16849. return Mesh._FRONTSIDE;
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Object.defineProperty(Mesh, "BACKSIDE", {
  16855. /**
  16856. * Mesh side orientation : usually the internal or back surface
  16857. */
  16858. get: function () {
  16859. return Mesh._BACKSIDE;
  16860. },
  16861. enumerable: true,
  16862. configurable: true
  16863. });
  16864. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16865. /**
  16866. * Mesh side orientation : both internal and external or front and back surfaces
  16867. */
  16868. get: function () {
  16869. return Mesh._DOUBLESIDE;
  16870. },
  16871. enumerable: true,
  16872. configurable: true
  16873. });
  16874. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16875. /**
  16876. * Mesh side orientation : by default, `FRONTSIDE`
  16877. */
  16878. get: function () {
  16879. return Mesh._DEFAULTSIDE;
  16880. },
  16881. enumerable: true,
  16882. configurable: true
  16883. });
  16884. Object.defineProperty(Mesh, "NO_CAP", {
  16885. /**
  16886. * Mesh cap setting : no cap
  16887. */
  16888. get: function () {
  16889. return Mesh._NO_CAP;
  16890. },
  16891. enumerable: true,
  16892. configurable: true
  16893. });
  16894. Object.defineProperty(Mesh, "CAP_START", {
  16895. /**
  16896. * Mesh cap setting : one cap at the beginning of the mesh
  16897. */
  16898. get: function () {
  16899. return Mesh._CAP_START;
  16900. },
  16901. enumerable: true,
  16902. configurable: true
  16903. });
  16904. Object.defineProperty(Mesh, "CAP_END", {
  16905. /**
  16906. * Mesh cap setting : one cap at the end of the mesh
  16907. */
  16908. get: function () {
  16909. return Mesh._CAP_END;
  16910. },
  16911. enumerable: true,
  16912. configurable: true
  16913. });
  16914. Object.defineProperty(Mesh, "CAP_ALL", {
  16915. /**
  16916. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  16917. */
  16918. get: function () {
  16919. return Mesh._CAP_ALL;
  16920. },
  16921. enumerable: true,
  16922. configurable: true
  16923. });
  16924. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  16925. set: function (callback) {
  16926. if (this._onBeforeDrawObserver) {
  16927. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  16928. }
  16929. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  16930. },
  16931. enumerable: true,
  16932. configurable: true
  16933. });
  16934. // Methods
  16935. /**
  16936. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16937. */
  16938. Mesh.prototype.toString = function (fullDetails) {
  16939. var ret = _super.prototype.toString.call(this, fullDetails);
  16940. ret += ", n vertices: " + this.getTotalVertices();
  16941. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16942. if (this.animations) {
  16943. for (var i = 0; i < this.animations.length; i++) {
  16944. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16945. }
  16946. }
  16947. if (fullDetails) {
  16948. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16949. }
  16950. return ret;
  16951. };
  16952. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16953. get: function () {
  16954. return this._LODLevels.length > 0;
  16955. },
  16956. enumerable: true,
  16957. configurable: true
  16958. });
  16959. Mesh.prototype._sortLODLevels = function () {
  16960. this._LODLevels.sort(function (a, b) {
  16961. if (a.distance < b.distance) {
  16962. return 1;
  16963. }
  16964. if (a.distance > b.distance) {
  16965. return -1;
  16966. }
  16967. return 0;
  16968. });
  16969. };
  16970. /**
  16971. * Add a mesh as LOD level triggered at the given distance.
  16972. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16973. * @param {number} distance - the distance from the center of the object to show this level
  16974. * @param {Mesh} mesh - the mesh to be added as LOD level
  16975. * @return {Mesh} this mesh (for chaining)
  16976. */
  16977. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16978. if (mesh && mesh._masterMesh) {
  16979. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16980. return this;
  16981. }
  16982. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16983. this._LODLevels.push(level);
  16984. if (mesh) {
  16985. mesh._masterMesh = this;
  16986. }
  16987. this._sortLODLevels();
  16988. return this;
  16989. };
  16990. /**
  16991. * Returns the LOD level mesh at the passed distance or null if not found.
  16992. * It is related to the method `addLODLevel(distance, mesh)`.
  16993. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16994. */
  16995. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16996. for (var index = 0; index < this._LODLevels.length; index++) {
  16997. var level = this._LODLevels[index];
  16998. if (level.distance === distance) {
  16999. return level.mesh;
  17000. }
  17001. }
  17002. return null;
  17003. };
  17004. /**
  17005. * Remove a mesh from the LOD array
  17006. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17007. * @param {Mesh} mesh - the mesh to be removed.
  17008. * @return {Mesh} this mesh (for chaining)
  17009. */
  17010. Mesh.prototype.removeLODLevel = function (mesh) {
  17011. for (var index = 0; index < this._LODLevels.length; index++) {
  17012. if (this._LODLevels[index].mesh === mesh) {
  17013. this._LODLevels.splice(index, 1);
  17014. if (mesh) {
  17015. mesh._masterMesh = null;
  17016. }
  17017. }
  17018. }
  17019. this._sortLODLevels();
  17020. return this;
  17021. };
  17022. /**
  17023. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  17024. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17025. */
  17026. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  17027. if (!this._LODLevels || this._LODLevels.length === 0) {
  17028. return this;
  17029. }
  17030. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  17031. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  17032. if (this.onLODLevelSelection) {
  17033. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  17034. }
  17035. return this;
  17036. }
  17037. for (var index = 0; index < this._LODLevels.length; index++) {
  17038. var level = this._LODLevels[index];
  17039. if (level.distance < distanceToCamera) {
  17040. if (level.mesh) {
  17041. level.mesh._preActivate();
  17042. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17043. }
  17044. if (this.onLODLevelSelection) {
  17045. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  17046. }
  17047. return level.mesh;
  17048. }
  17049. }
  17050. if (this.onLODLevelSelection) {
  17051. this.onLODLevelSelection(distanceToCamera, this, this);
  17052. }
  17053. return this;
  17054. };
  17055. Object.defineProperty(Mesh.prototype, "geometry", {
  17056. /**
  17057. * Returns the mesh internal `Geometry` object.
  17058. */
  17059. get: function () {
  17060. return this._geometry;
  17061. },
  17062. enumerable: true,
  17063. configurable: true
  17064. });
  17065. /**
  17066. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  17067. */
  17068. Mesh.prototype.getTotalVertices = function () {
  17069. if (!this._geometry) {
  17070. return 0;
  17071. }
  17072. return this._geometry.getTotalVertices();
  17073. };
  17074. /**
  17075. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  17076. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  17077. * Returns null if the mesh has no geometry or no vertex buffer.
  17078. * Possible `kind` values :
  17079. * - BABYLON.VertexBuffer.PositionKind
  17080. * - BABYLON.VertexBuffer.UVKind
  17081. * - BABYLON.VertexBuffer.UV2Kind
  17082. * - BABYLON.VertexBuffer.UV3Kind
  17083. * - BABYLON.VertexBuffer.UV4Kind
  17084. * - BABYLON.VertexBuffer.UV5Kind
  17085. * - BABYLON.VertexBuffer.UV6Kind
  17086. * - BABYLON.VertexBuffer.ColorKind
  17087. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17088. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17089. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17090. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17091. */
  17092. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17093. if (!this._geometry) {
  17094. return null;
  17095. }
  17096. return this._geometry.getVerticesData(kind, copyWhenShared);
  17097. };
  17098. /**
  17099. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  17100. * Returns `undefined` if the mesh has no geometry.
  17101. * Possible `kind` values :
  17102. * - BABYLON.VertexBuffer.PositionKind
  17103. * - BABYLON.VertexBuffer.UVKind
  17104. * - BABYLON.VertexBuffer.UV2Kind
  17105. * - BABYLON.VertexBuffer.UV3Kind
  17106. * - BABYLON.VertexBuffer.UV4Kind
  17107. * - BABYLON.VertexBuffer.UV5Kind
  17108. * - BABYLON.VertexBuffer.UV6Kind
  17109. * - BABYLON.VertexBuffer.ColorKind
  17110. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17111. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17112. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17113. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17114. */
  17115. Mesh.prototype.getVertexBuffer = function (kind) {
  17116. if (!this._geometry) {
  17117. return undefined;
  17118. }
  17119. return this._geometry.getVertexBuffer(kind);
  17120. };
  17121. /**
  17122. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17123. * Possible `kind` values :
  17124. * - BABYLON.VertexBuffer.PositionKind
  17125. * - BABYLON.VertexBuffer.UVKind
  17126. * - BABYLON.VertexBuffer.UV2Kind
  17127. * - BABYLON.VertexBuffer.UV3Kind
  17128. * - BABYLON.VertexBuffer.UV4Kind
  17129. * - BABYLON.VertexBuffer.UV5Kind
  17130. * - BABYLON.VertexBuffer.UV6Kind
  17131. * - BABYLON.VertexBuffer.ColorKind
  17132. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17133. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17134. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17135. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17136. */
  17137. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17138. if (!this._geometry) {
  17139. if (this._delayInfo) {
  17140. return this._delayInfo.indexOf(kind) !== -1;
  17141. }
  17142. return false;
  17143. }
  17144. return this._geometry.isVerticesDataPresent(kind);
  17145. };
  17146. /**
  17147. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17148. * Possible `kind` values :
  17149. * - BABYLON.VertexBuffer.PositionKind
  17150. * - BABYLON.VertexBuffer.UVKind
  17151. * - BABYLON.VertexBuffer.UV2Kind
  17152. * - BABYLON.VertexBuffer.UV3Kind
  17153. * - BABYLON.VertexBuffer.UV4Kind
  17154. * - BABYLON.VertexBuffer.UV5Kind
  17155. * - BABYLON.VertexBuffer.UV6Kind
  17156. * - BABYLON.VertexBuffer.ColorKind
  17157. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17158. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17159. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17160. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17161. */
  17162. Mesh.prototype.getVerticesDataKinds = function () {
  17163. if (!this._geometry) {
  17164. var result = [];
  17165. if (this._delayInfo) {
  17166. for (var kind in this._delayInfo) {
  17167. result.push(kind);
  17168. }
  17169. }
  17170. return result;
  17171. }
  17172. return this._geometry.getVerticesDataKinds();
  17173. };
  17174. /**
  17175. * Returns a positive integer : the total number of indices in this mesh geometry.
  17176. * Returns zero if the mesh has no geometry.
  17177. */
  17178. Mesh.prototype.getTotalIndices = function () {
  17179. if (!this._geometry) {
  17180. return 0;
  17181. }
  17182. return this._geometry.getTotalIndices();
  17183. };
  17184. /**
  17185. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17186. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  17187. * Returns an empty array if the mesh has no geometry.
  17188. */
  17189. Mesh.prototype.getIndices = function (copyWhenShared) {
  17190. if (!this._geometry) {
  17191. return [];
  17192. }
  17193. return this._geometry.getIndices(copyWhenShared);
  17194. };
  17195. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17196. get: function () {
  17197. return this._masterMesh !== null && this._masterMesh !== undefined;
  17198. },
  17199. enumerable: true,
  17200. configurable: true
  17201. });
  17202. /**
  17203. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17204. */
  17205. Mesh.prototype.isReady = function () {
  17206. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17207. return false;
  17208. }
  17209. return _super.prototype.isReady.call(this);
  17210. };
  17211. /**
  17212. * Boolean : true if the mesh has been disposed.
  17213. */
  17214. Mesh.prototype.isDisposed = function () {
  17215. return this._isDisposed;
  17216. };
  17217. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17218. get: function () {
  17219. return this._sideOrientation;
  17220. },
  17221. /**
  17222. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17223. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17224. */
  17225. set: function (sideO) {
  17226. this._sideOrientation = sideO;
  17227. },
  17228. enumerable: true,
  17229. configurable: true
  17230. });
  17231. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17232. /**
  17233. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17234. * This property is pertinent only for updatable parametric shapes.
  17235. */
  17236. get: function () {
  17237. return this._areNormalsFrozen;
  17238. },
  17239. enumerable: true,
  17240. configurable: true
  17241. });
  17242. /**
  17243. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17244. * It has no effect at all on other shapes.
  17245. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17246. */
  17247. Mesh.prototype.freezeNormals = function () {
  17248. this._areNormalsFrozen = true;
  17249. };
  17250. /**
  17251. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17252. * It has no effect at all on other shapes.
  17253. * It reactivates the mesh normals computation if it was previously frozen.
  17254. */
  17255. Mesh.prototype.unfreezeNormals = function () {
  17256. this._areNormalsFrozen = false;
  17257. };
  17258. // Methods
  17259. Mesh.prototype._preActivate = function () {
  17260. var sceneRenderId = this.getScene().getRenderId();
  17261. if (this._preActivateId === sceneRenderId) {
  17262. return;
  17263. }
  17264. this._preActivateId = sceneRenderId;
  17265. this._visibleInstances = null;
  17266. };
  17267. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17268. if (this._visibleInstances) {
  17269. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17270. }
  17271. };
  17272. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17273. if (!this._visibleInstances) {
  17274. this._visibleInstances = {};
  17275. this._visibleInstances.defaultRenderId = renderId;
  17276. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17277. }
  17278. if (!this._visibleInstances[renderId]) {
  17279. this._visibleInstances[renderId] = new Array();
  17280. }
  17281. this._visibleInstances[renderId].push(instance);
  17282. };
  17283. /**
  17284. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17285. * This means the mesh underlying bounding box and sphere are recomputed.
  17286. */
  17287. Mesh.prototype.refreshBoundingInfo = function () {
  17288. if (this._boundingInfo.isLocked) {
  17289. return;
  17290. }
  17291. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17292. if (data) {
  17293. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17294. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17295. }
  17296. if (this.subMeshes) {
  17297. for (var index = 0; index < this.subMeshes.length; index++) {
  17298. this.subMeshes[index].refreshBoundingInfo();
  17299. }
  17300. }
  17301. this._updateBoundingInfo();
  17302. };
  17303. Mesh.prototype._createGlobalSubMesh = function () {
  17304. var totalVertices = this.getTotalVertices();
  17305. if (!totalVertices || !this.getIndices()) {
  17306. return null;
  17307. }
  17308. this.releaseSubMeshes();
  17309. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17310. };
  17311. Mesh.prototype.subdivide = function (count) {
  17312. if (count < 1) {
  17313. return;
  17314. }
  17315. var totalIndices = this.getTotalIndices();
  17316. var subdivisionSize = (totalIndices / count) | 0;
  17317. var offset = 0;
  17318. // Ensure that subdivisionSize is a multiple of 3
  17319. while (subdivisionSize % 3 !== 0) {
  17320. subdivisionSize++;
  17321. }
  17322. this.releaseSubMeshes();
  17323. for (var index = 0; index < count; index++) {
  17324. if (offset >= totalIndices) {
  17325. break;
  17326. }
  17327. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17328. offset += subdivisionSize;
  17329. }
  17330. this.synchronizeInstances();
  17331. };
  17332. /**
  17333. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17334. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17335. * The `data` are either a numeric array either a Float32Array.
  17336. * The parameter `updatable` is passed as is to the underlying `Geometry` object constructor (if initianilly none) or updater.
  17337. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  17338. * Note that a new underlying `VertexBuffer` object is created each call.
  17339. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17340. *
  17341. * Possible `kind` values :
  17342. * - BABYLON.VertexBuffer.PositionKind
  17343. * - BABYLON.VertexBuffer.UVKind
  17344. * - BABYLON.VertexBuffer.UV2Kind
  17345. * - BABYLON.VertexBuffer.UV3Kind
  17346. * - BABYLON.VertexBuffer.UV4Kind
  17347. * - BABYLON.VertexBuffer.UV5Kind
  17348. * - BABYLON.VertexBuffer.UV6Kind
  17349. * - BABYLON.VertexBuffer.ColorKind
  17350. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17351. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17352. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17353. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17354. */
  17355. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17356. if (!this._geometry) {
  17357. var vertexData = new BABYLON.VertexData();
  17358. vertexData.set(data, kind);
  17359. var scene = this.getScene();
  17360. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17361. }
  17362. else {
  17363. this._geometry.setVerticesData(kind, data, updatable, stride);
  17364. }
  17365. };
  17366. /**
  17367. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17368. * If the mesh has no geometry, it is simply returned as it is.
  17369. * The `data` are either a numeric array either a Float32Array.
  17370. * No new underlying `VertexBuffer` object is created.
  17371. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17372. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17373. *
  17374. * Possible `kind` values :
  17375. * - BABYLON.VertexBuffer.PositionKind
  17376. * - BABYLON.VertexBuffer.UVKind
  17377. * - BABYLON.VertexBuffer.UV2Kind
  17378. * - BABYLON.VertexBuffer.UV3Kind
  17379. * - BABYLON.VertexBuffer.UV4Kind
  17380. * - BABYLON.VertexBuffer.UV5Kind
  17381. * - BABYLON.VertexBuffer.UV6Kind
  17382. * - BABYLON.VertexBuffer.ColorKind
  17383. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17384. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17385. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17386. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17387. */
  17388. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17389. if (!this._geometry) {
  17390. return;
  17391. }
  17392. if (!makeItUnique) {
  17393. this._geometry.updateVerticesData(kind, data, updateExtends);
  17394. }
  17395. else {
  17396. this.makeGeometryUnique();
  17397. this.updateVerticesData(kind, data, updateExtends, false);
  17398. }
  17399. };
  17400. /**
  17401. * Deprecated since BabylonJS v2.3
  17402. */
  17403. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17404. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17405. if (!this._geometry) {
  17406. return;
  17407. }
  17408. if (!makeItUnique) {
  17409. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17410. }
  17411. else {
  17412. this.makeGeometryUnique();
  17413. this.updateVerticesDataDirectly(kind, data, offset, false);
  17414. }
  17415. };
  17416. /**
  17417. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17418. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17419. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17420. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17421. */
  17422. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17423. if (computeNormals === void 0) { computeNormals = true; }
  17424. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17425. positionFunction(positions);
  17426. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17427. if (computeNormals) {
  17428. var indices = this.getIndices();
  17429. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17430. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17431. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17432. }
  17433. };
  17434. Mesh.prototype.makeGeometryUnique = function () {
  17435. if (!this._geometry) {
  17436. return;
  17437. }
  17438. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17439. geometry.applyToMesh(this);
  17440. };
  17441. /**
  17442. * Sets the mesh indices.
  17443. * Expects an array populated with integers or a Int32Array.
  17444. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17445. * This method creates a new index buffer each call.
  17446. */
  17447. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17448. if (!this._geometry) {
  17449. var vertexData = new BABYLON.VertexData();
  17450. vertexData.indices = indices;
  17451. var scene = this.getScene();
  17452. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17453. }
  17454. else {
  17455. this._geometry.setIndices(indices, totalVertices);
  17456. }
  17457. };
  17458. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17459. var engine = this.getScene().getEngine();
  17460. // Wireframe
  17461. var indexToBind;
  17462. if (this._unIndexed) {
  17463. indexToBind = null;
  17464. }
  17465. else {
  17466. switch (fillMode) {
  17467. case BABYLON.Material.PointFillMode:
  17468. indexToBind = null;
  17469. break;
  17470. case BABYLON.Material.WireFrameFillMode:
  17471. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17472. break;
  17473. default:
  17474. case BABYLON.Material.TriangleFillMode:
  17475. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17476. break;
  17477. }
  17478. }
  17479. // VBOs
  17480. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17481. };
  17482. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17483. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17484. return;
  17485. }
  17486. this.onBeforeDrawObservable.notifyObservers(this);
  17487. var engine = this.getScene().getEngine();
  17488. // Draw order
  17489. switch (fillMode) {
  17490. case BABYLON.Material.PointFillMode:
  17491. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17492. break;
  17493. case BABYLON.Material.WireFrameFillMode:
  17494. if (this._unIndexed) {
  17495. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17496. }
  17497. else {
  17498. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17499. }
  17500. break;
  17501. default:
  17502. if (this._unIndexed) {
  17503. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17504. }
  17505. else {
  17506. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17507. }
  17508. }
  17509. };
  17510. /**
  17511. * Registers for this mesh a javascript function called just before the rendering process.
  17512. * This function is passed the current mesh and doesn't return anything.
  17513. */
  17514. Mesh.prototype.registerBeforeRender = function (func) {
  17515. this.onBeforeRenderObservable.add(func);
  17516. };
  17517. /**
  17518. * Disposes a previously registered javascript function called before the rendering.
  17519. * This function is passed the current mesh and doesn't return anything.
  17520. */
  17521. Mesh.prototype.unregisterBeforeRender = function (func) {
  17522. this.onBeforeRenderObservable.removeCallback(func);
  17523. };
  17524. /**
  17525. * Registers for this mesh a javascript function called just after the rendering is complete.
  17526. * This function is passed the current mesh and doesn't return anything.
  17527. */
  17528. Mesh.prototype.registerAfterRender = function (func) {
  17529. this.onAfterRenderObservable.add(func);
  17530. };
  17531. /**
  17532. * Disposes a previously registered javascript function called after the rendering.
  17533. * This function is passed the current mesh and doesn't return anything.
  17534. */
  17535. Mesh.prototype.unregisterAfterRender = function (func) {
  17536. this.onAfterRenderObservable.removeCallback(func);
  17537. };
  17538. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17539. var scene = this.getScene();
  17540. this._batchCache.mustReturn = false;
  17541. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17542. this._batchCache.visibleInstances[subMeshId] = null;
  17543. if (this._visibleInstances) {
  17544. var currentRenderId = scene.getRenderId();
  17545. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17546. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17547. var selfRenderId = this._renderId;
  17548. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17549. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17550. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17551. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17552. }
  17553. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17554. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17555. this._batchCache.mustReturn = true;
  17556. return this._batchCache;
  17557. }
  17558. if (currentRenderId !== selfRenderId) {
  17559. this._batchCache.renderSelf[subMeshId] = false;
  17560. }
  17561. }
  17562. this._renderIdForInstances[subMeshId] = currentRenderId;
  17563. }
  17564. return this._batchCache;
  17565. };
  17566. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17567. var visibleInstances = batch.visibleInstances[subMesh._id];
  17568. var matricesCount = visibleInstances.length + 1;
  17569. var bufferSize = matricesCount * 16 * 4;
  17570. while (this._instancesBufferSize < bufferSize) {
  17571. this._instancesBufferSize *= 2;
  17572. }
  17573. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17574. if (this._worldMatricesInstancesBuffer) {
  17575. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17576. }
  17577. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17578. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17579. }
  17580. var offset = 0;
  17581. var instancesCount = 0;
  17582. var world = this.getWorldMatrix();
  17583. if (batch.renderSelf[subMesh._id]) {
  17584. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17585. offset += 16;
  17586. instancesCount++;
  17587. }
  17588. if (visibleInstances) {
  17589. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17590. var instance = visibleInstances[instanceIndex];
  17591. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17592. offset += 16;
  17593. instancesCount++;
  17594. }
  17595. }
  17596. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17597. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17598. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17599. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17600. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17601. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17602. this._draw(subMesh, fillMode, instancesCount);
  17603. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17604. };
  17605. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17606. var scene = this.getScene();
  17607. var engine = scene.getEngine();
  17608. if (hardwareInstancedRendering) {
  17609. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17610. }
  17611. else {
  17612. if (batch.renderSelf[subMesh._id]) {
  17613. // Draw
  17614. if (onBeforeDraw) {
  17615. onBeforeDraw(false, this.getWorldMatrix());
  17616. }
  17617. this._draw(subMesh, fillMode);
  17618. }
  17619. if (batch.visibleInstances[subMesh._id]) {
  17620. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17621. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17622. // World
  17623. var world = instance.getWorldMatrix();
  17624. if (onBeforeDraw) {
  17625. onBeforeDraw(true, world);
  17626. }
  17627. // Draw
  17628. this._draw(subMesh, fillMode);
  17629. }
  17630. }
  17631. }
  17632. };
  17633. /**
  17634. * Triggers the draw call for the mesh.
  17635. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  17636. */
  17637. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17638. var scene = this.getScene();
  17639. // Managing instances
  17640. var batch = this._getInstancesRenderList(subMesh._id);
  17641. if (batch.mustReturn) {
  17642. return;
  17643. }
  17644. // Checking geometry state
  17645. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17646. return;
  17647. }
  17648. var callbackIndex;
  17649. this.onBeforeRenderObservable.notifyObservers(this);
  17650. var engine = scene.getEngine();
  17651. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17652. // Material
  17653. var effectiveMaterial = subMesh.getMaterial();
  17654. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17655. return;
  17656. }
  17657. // Outline - step 1
  17658. var savedDepthWrite = engine.getDepthWrite();
  17659. if (this.renderOutline) {
  17660. engine.setDepthWrite(false);
  17661. scene.getOutlineRenderer().render(subMesh, batch);
  17662. engine.setDepthWrite(savedDepthWrite);
  17663. }
  17664. effectiveMaterial._preBind();
  17665. var effect = effectiveMaterial.getEffect();
  17666. // Bind
  17667. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17668. this._bind(subMesh, effect, fillMode);
  17669. var world = this.getWorldMatrix();
  17670. effectiveMaterial.bind(world, this);
  17671. // Alpha mode
  17672. if (enableAlphaMode) {
  17673. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17674. }
  17675. // Draw
  17676. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17677. if (isInstance) {
  17678. effectiveMaterial.bindOnlyWorldMatrix(world);
  17679. }
  17680. });
  17681. // Unbind
  17682. effectiveMaterial.unbind();
  17683. // Outline - step 2
  17684. if (this.renderOutline && savedDepthWrite) {
  17685. engine.setDepthWrite(true);
  17686. engine.setColorWrite(false);
  17687. scene.getOutlineRenderer().render(subMesh, batch);
  17688. engine.setColorWrite(true);
  17689. }
  17690. // Overlay
  17691. if (this.renderOverlay) {
  17692. var currentMode = engine.getAlphaMode();
  17693. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17694. scene.getOutlineRenderer().render(subMesh, batch, true);
  17695. engine.setAlphaMode(currentMode);
  17696. }
  17697. this.onAfterRenderObservable.notifyObservers(this);
  17698. };
  17699. /**
  17700. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  17701. */
  17702. Mesh.prototype.getEmittedParticleSystems = function () {
  17703. var results = new Array();
  17704. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17705. var particleSystem = this.getScene().particleSystems[index];
  17706. if (particleSystem.emitter === this) {
  17707. results.push(particleSystem);
  17708. }
  17709. }
  17710. return results;
  17711. };
  17712. /**
  17713. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  17714. */
  17715. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17716. var results = new Array();
  17717. var descendants = this.getDescendants();
  17718. descendants.push(this);
  17719. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17720. var particleSystem = this.getScene().particleSystems[index];
  17721. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17722. results.push(particleSystem);
  17723. }
  17724. }
  17725. return results;
  17726. };
  17727. Mesh.prototype._checkDelayState = function () {
  17728. var _this = this;
  17729. var that = this;
  17730. var scene = this.getScene();
  17731. if (this._geometry) {
  17732. this._geometry.load(scene);
  17733. }
  17734. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17735. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17736. scene._addPendingData(that);
  17737. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17738. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17739. if (data instanceof ArrayBuffer) {
  17740. _this._delayLoadingFunction(data, _this);
  17741. }
  17742. else {
  17743. _this._delayLoadingFunction(JSON.parse(data), _this);
  17744. }
  17745. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17746. scene._removePendingData(_this);
  17747. }, function () { }, scene.database, getBinaryData);
  17748. }
  17749. };
  17750. /**
  17751. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  17752. */
  17753. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17754. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17755. return false;
  17756. }
  17757. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17758. return false;
  17759. }
  17760. this._checkDelayState();
  17761. return true;
  17762. };
  17763. /**
  17764. * Sets the mesh material by the material or multiMaterial `id` property.
  17765. * The material `id` is a string identifying the material or the multiMaterial.
  17766. * This method returns nothing.
  17767. */
  17768. Mesh.prototype.setMaterialByID = function (id) {
  17769. var materials = this.getScene().materials;
  17770. var index;
  17771. for (index = 0; index < materials.length; index++) {
  17772. if (materials[index].id === id) {
  17773. this.material = materials[index];
  17774. return;
  17775. }
  17776. }
  17777. // Multi
  17778. var multiMaterials = this.getScene().multiMaterials;
  17779. for (index = 0; index < multiMaterials.length; index++) {
  17780. if (multiMaterials[index].id === id) {
  17781. this.material = multiMaterials[index];
  17782. return;
  17783. }
  17784. }
  17785. };
  17786. /**
  17787. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  17788. */
  17789. Mesh.prototype.getAnimatables = function () {
  17790. var results = [];
  17791. if (this.material) {
  17792. results.push(this.material);
  17793. }
  17794. if (this.skeleton) {
  17795. results.push(this.skeleton);
  17796. }
  17797. return results;
  17798. };
  17799. /**
  17800. * Modifies the mesh geometry according to the passed transformation matrix.
  17801. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  17802. * The mesh normals are modified accordingly the same transformation.
  17803. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  17804. * Note that, under the hood, this method sets a new VertexBuffer each call.
  17805. */
  17806. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17807. // Position
  17808. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17809. return;
  17810. }
  17811. this._resetPointsArrayCache();
  17812. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17813. var temp = [];
  17814. var index;
  17815. for (index = 0; index < data.length; index += 3) {
  17816. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  17817. }
  17818. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  17819. // Normals
  17820. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17821. return;
  17822. }
  17823. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17824. temp = [];
  17825. for (index = 0; index < data.length; index += 3) {
  17826. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  17827. }
  17828. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  17829. // flip faces?
  17830. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  17831. this.flipFaces();
  17832. }
  17833. };
  17834. /**
  17835. * Modifies the mesh geometry according to its own current World Matrix.
  17836. * The mesh World Matrix is then reset.
  17837. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  17838. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  17839. * Note that, under the hood, this method sets a new VertexBuffer each call.
  17840. */
  17841. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  17842. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  17843. this.scaling.copyFromFloats(1, 1, 1);
  17844. this.position.copyFromFloats(0, 0, 0);
  17845. this.rotation.copyFromFloats(0, 0, 0);
  17846. //only if quaternion is already set
  17847. if (this.rotationQuaternion) {
  17848. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  17849. }
  17850. this._worldMatrix = BABYLON.Matrix.Identity();
  17851. };
  17852. // Cache
  17853. Mesh.prototype._resetPointsArrayCache = function () {
  17854. this._positions = null;
  17855. };
  17856. Mesh.prototype._generatePointsArray = function () {
  17857. if (this._positions)
  17858. return true;
  17859. this._positions = [];
  17860. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17861. if (!data) {
  17862. return false;
  17863. }
  17864. for (var index = 0; index < data.length; index += 3) {
  17865. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  17866. }
  17867. return true;
  17868. };
  17869. /**
  17870. * Returns a new `Mesh` object generated from the current mesh properties.
  17871. * This method must not get confused with createInstance().
  17872. * The parameter `name` is a string, the name given to the new mesh.
  17873. * The optional parameter `newParent` can be any `Node` object (default `null`).
  17874. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  17875. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  17876. */
  17877. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  17878. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17879. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  17880. };
  17881. /**
  17882. * Disposes the mesh.
  17883. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  17884. */
  17885. Mesh.prototype.dispose = function (doNotRecurse) {
  17886. if (this._geometry) {
  17887. this._geometry.releaseForMesh(this, true);
  17888. }
  17889. // Instances
  17890. if (this._worldMatricesInstancesBuffer) {
  17891. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17892. this._worldMatricesInstancesBuffer = null;
  17893. }
  17894. while (this.instances.length) {
  17895. this.instances[0].dispose();
  17896. }
  17897. _super.prototype.dispose.call(this, doNotRecurse);
  17898. };
  17899. /**
  17900. * Modifies the mesh geometry according to a displacement map.
  17901. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  17902. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  17903. * This method returns nothing.
  17904. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  17905. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  17906. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  17907. */
  17908. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  17909. var _this = this;
  17910. var scene = this.getScene();
  17911. var onload = function (img) {
  17912. // Getting height map data
  17913. var canvas = document.createElement("canvas");
  17914. var context = canvas.getContext("2d");
  17915. var heightMapWidth = img.width;
  17916. var heightMapHeight = img.height;
  17917. canvas.width = heightMapWidth;
  17918. canvas.height = heightMapHeight;
  17919. context.drawImage(img, 0, 0);
  17920. // Create VertexData from map data
  17921. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17922. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  17923. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  17924. //execute success callback, if set
  17925. if (onSuccess) {
  17926. onSuccess(_this);
  17927. }
  17928. };
  17929. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17930. };
  17931. /**
  17932. * Modifies the mesh geometry according to a displacementMap buffer.
  17933. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  17934. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  17935. * This method returns nothing.
  17936. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  17937. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  17938. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  17939. */
  17940. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  17941. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  17942. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  17943. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17944. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  17945. return;
  17946. }
  17947. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17948. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17949. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17950. var position = BABYLON.Vector3.Zero();
  17951. var normal = BABYLON.Vector3.Zero();
  17952. var uv = BABYLON.Vector2.Zero();
  17953. for (var index = 0; index < positions.length; index += 3) {
  17954. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  17955. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  17956. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  17957. // Compute height
  17958. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  17959. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  17960. var pos = (u + v * heightMapWidth) * 4;
  17961. var r = buffer[pos] / 255.0;
  17962. var g = buffer[pos + 1] / 255.0;
  17963. var b = buffer[pos + 2] / 255.0;
  17964. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17965. normal.normalize();
  17966. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  17967. position = position.add(normal);
  17968. position.toArray(positions, index);
  17969. }
  17970. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  17971. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  17972. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17973. };
  17974. /**
  17975. * Modify the mesh to get a flat shading rendering.
  17976. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  17977. * This method returns nothing.
  17978. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  17979. */
  17980. Mesh.prototype.convertToFlatShadedMesh = function () {
  17981. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  17982. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17983. var kinds = this.getVerticesDataKinds();
  17984. var vbs = [];
  17985. var data = [];
  17986. var newdata = [];
  17987. var updatableNormals = false;
  17988. var kindIndex;
  17989. var kind;
  17990. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17991. kind = kinds[kindIndex];
  17992. var vertexBuffer = this.getVertexBuffer(kind);
  17993. if (kind === BABYLON.VertexBuffer.NormalKind) {
  17994. updatableNormals = vertexBuffer.isUpdatable();
  17995. kinds.splice(kindIndex, 1);
  17996. kindIndex--;
  17997. continue;
  17998. }
  17999. vbs[kind] = vertexBuffer;
  18000. data[kind] = vbs[kind].getData();
  18001. newdata[kind] = [];
  18002. }
  18003. // Save previous submeshes
  18004. var previousSubmeshes = this.subMeshes.slice(0);
  18005. var indices = this.getIndices();
  18006. var totalIndices = this.getTotalIndices();
  18007. // Generating unique vertices per face
  18008. var index;
  18009. for (index = 0; index < totalIndices; index++) {
  18010. var vertexIndex = indices[index];
  18011. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18012. kind = kinds[kindIndex];
  18013. var stride = vbs[kind].getStrideSize();
  18014. for (var offset = 0; offset < stride; offset++) {
  18015. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18016. }
  18017. }
  18018. }
  18019. // Updating faces & normal
  18020. var normals = [];
  18021. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  18022. for (index = 0; index < totalIndices; index += 3) {
  18023. indices[index] = index;
  18024. indices[index + 1] = index + 1;
  18025. indices[index + 2] = index + 2;
  18026. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  18027. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  18028. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  18029. var p1p2 = p1.subtract(p2);
  18030. var p3p2 = p3.subtract(p2);
  18031. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18032. // Store same normals for every vertex
  18033. for (var localIndex = 0; localIndex < 3; localIndex++) {
  18034. normals.push(normal.x);
  18035. normals.push(normal.y);
  18036. normals.push(normal.z);
  18037. }
  18038. }
  18039. this.setIndices(indices);
  18040. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  18041. // Updating vertex buffers
  18042. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18043. kind = kinds[kindIndex];
  18044. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18045. }
  18046. // Updating submeshes
  18047. this.releaseSubMeshes();
  18048. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18049. var previousOne = previousSubmeshes[submeshIndex];
  18050. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18051. }
  18052. this.synchronizeInstances();
  18053. };
  18054. /**
  18055. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  18056. * In other words, more vertices, no more indices and a single bigger VBO.
  18057. * This method returns nothing.
  18058. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  18059. *
  18060. */
  18061. Mesh.prototype.convertToUnIndexedMesh = function () {
  18062. /// <summary>Remove indices by unfolding faces into buffers</summary>
  18063. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18064. var kinds = this.getVerticesDataKinds();
  18065. var vbs = [];
  18066. var data = [];
  18067. var newdata = [];
  18068. var updatableNormals = false;
  18069. var kindIndex;
  18070. var kind;
  18071. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18072. kind = kinds[kindIndex];
  18073. var vertexBuffer = this.getVertexBuffer(kind);
  18074. vbs[kind] = vertexBuffer;
  18075. data[kind] = vbs[kind].getData();
  18076. newdata[kind] = [];
  18077. }
  18078. // Save previous submeshes
  18079. var previousSubmeshes = this.subMeshes.slice(0);
  18080. var indices = this.getIndices();
  18081. var totalIndices = this.getTotalIndices();
  18082. // Generating unique vertices per face
  18083. var index;
  18084. for (index = 0; index < totalIndices; index++) {
  18085. var vertexIndex = indices[index];
  18086. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18087. kind = kinds[kindIndex];
  18088. var stride = vbs[kind].getStrideSize();
  18089. for (var offset = 0; offset < stride; offset++) {
  18090. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18091. }
  18092. }
  18093. }
  18094. // Updating indices
  18095. for (index = 0; index < totalIndices; index += 3) {
  18096. indices[index] = index;
  18097. indices[index + 1] = index + 1;
  18098. indices[index + 2] = index + 2;
  18099. }
  18100. this.setIndices(indices);
  18101. // Updating vertex buffers
  18102. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18103. kind = kinds[kindIndex];
  18104. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18105. }
  18106. // Updating submeshes
  18107. this.releaseSubMeshes();
  18108. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18109. var previousOne = previousSubmeshes[submeshIndex];
  18110. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18111. }
  18112. this._unIndexed = true;
  18113. this.synchronizeInstances();
  18114. };
  18115. /**
  18116. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  18117. * This method returns nothing.
  18118. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  18119. */
  18120. Mesh.prototype.flipFaces = function (flipNormals) {
  18121. if (flipNormals === void 0) { flipNormals = false; }
  18122. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  18123. var i;
  18124. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18125. for (i = 0; i < vertex_data.normals.length; i++) {
  18126. vertex_data.normals[i] *= -1;
  18127. }
  18128. }
  18129. var temp;
  18130. for (i = 0; i < vertex_data.indices.length; i += 3) {
  18131. // reassign indices
  18132. temp = vertex_data.indices[i + 1];
  18133. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  18134. vertex_data.indices[i + 2] = temp;
  18135. }
  18136. vertex_data.applyToMesh(this);
  18137. };
  18138. // Instances
  18139. /**
  18140. * Creates a new `InstancedMesh` object from the mesh model.
  18141. * An instance shares the same properties and the same material than its model.
  18142. * Only these properties of each instance can then be set individually :
  18143. * - position
  18144. * - rotation
  18145. * - rotationQuaternion
  18146. * - setPivotMatrix
  18147. * - scaling
  18148. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  18149. * Warning : this method is not supported for `Line` mesh and `LineSystem`
  18150. */
  18151. Mesh.prototype.createInstance = function (name) {
  18152. return new BABYLON.InstancedMesh(name, this);
  18153. };
  18154. /**
  18155. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  18156. * After this call, all the mesh instances have the same submeshes than the current mesh.
  18157. * This method returns nothing.
  18158. */
  18159. Mesh.prototype.synchronizeInstances = function () {
  18160. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  18161. var instance = this.instances[instanceIndex];
  18162. instance._syncSubMeshes();
  18163. }
  18164. };
  18165. /**
  18166. * Simplify the mesh according to the given array of settings.
  18167. * Function will return immediately and will simplify async. It returns nothing.
  18168. * @param settings a collection of simplification settings.
  18169. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18170. * @param type the type of simplification to run.
  18171. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18172. */
  18173. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18174. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18175. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18176. this.getScene().simplificationQueue.addTask({
  18177. settings: settings,
  18178. parallelProcessing: parallelProcessing,
  18179. mesh: this,
  18180. simplificationType: simplificationType,
  18181. successCallback: successCallback
  18182. });
  18183. };
  18184. /**
  18185. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18186. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18187. * This should be used together with the simplification to avoid disappearing triangles.
  18188. * @param successCallback an optional success callback to be called after the optimization finished.
  18189. */
  18190. Mesh.prototype.optimizeIndices = function (successCallback) {
  18191. var _this = this;
  18192. var indices = this.getIndices();
  18193. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18194. var vectorPositions = [];
  18195. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18196. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18197. }
  18198. var dupes = [];
  18199. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18200. var realPos = vectorPositions.length - 1 - iteration;
  18201. var testedPosition = vectorPositions[realPos];
  18202. for (var j = 0; j < realPos; ++j) {
  18203. var againstPosition = vectorPositions[j];
  18204. if (testedPosition.equals(againstPosition)) {
  18205. dupes[realPos] = j;
  18206. break;
  18207. }
  18208. }
  18209. }, function () {
  18210. for (var i = 0; i < indices.length; ++i) {
  18211. indices[i] = dupes[indices[i]] || indices[i];
  18212. }
  18213. //indices are now reordered
  18214. var originalSubMeshes = _this.subMeshes.slice(0);
  18215. _this.setIndices(indices);
  18216. _this.subMeshes = originalSubMeshes;
  18217. if (successCallback) {
  18218. successCallback(_this);
  18219. }
  18220. });
  18221. };
  18222. // Statics
  18223. /**
  18224. * Returns a new `Mesh` object what is a deep copy of the passed mesh.
  18225. * The parameter `parsedMesh` is the mesh to be copied.
  18226. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18227. */
  18228. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18229. var mesh = new Mesh(parsedMesh.name, scene);
  18230. mesh.id = parsedMesh.id;
  18231. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18232. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18233. if (parsedMesh.rotationQuaternion) {
  18234. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18235. }
  18236. else if (parsedMesh.rotation) {
  18237. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18238. }
  18239. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18240. if (parsedMesh.localMatrix) {
  18241. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18242. }
  18243. else if (parsedMesh.pivotMatrix) {
  18244. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18245. }
  18246. mesh.setEnabled(parsedMesh.isEnabled);
  18247. mesh.isVisible = parsedMesh.isVisible;
  18248. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18249. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18250. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18251. if (parsedMesh.applyFog !== undefined) {
  18252. mesh.applyFog = parsedMesh.applyFog;
  18253. }
  18254. if (parsedMesh.pickable !== undefined) {
  18255. mesh.isPickable = parsedMesh.pickable;
  18256. }
  18257. if (parsedMesh.alphaIndex !== undefined) {
  18258. mesh.alphaIndex = parsedMesh.alphaIndex;
  18259. }
  18260. mesh.receiveShadows = parsedMesh.receiveShadows;
  18261. mesh.billboardMode = parsedMesh.billboardMode;
  18262. if (parsedMesh.visibility !== undefined) {
  18263. mesh.visibility = parsedMesh.visibility;
  18264. }
  18265. mesh.checkCollisions = parsedMesh.checkCollisions;
  18266. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18267. // freezeWorldMatrix
  18268. if (parsedMesh.freezeWorldMatrix) {
  18269. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18270. }
  18271. // Parent
  18272. if (parsedMesh.parentId) {
  18273. mesh._waitingParentId = parsedMesh.parentId;
  18274. }
  18275. // Actions
  18276. if (parsedMesh.actions !== undefined) {
  18277. mesh._waitingActions = parsedMesh.actions;
  18278. }
  18279. // Geometry
  18280. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18281. if (parsedMesh.delayLoadingFile) {
  18282. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18283. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18284. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18285. if (parsedMesh._binaryInfo) {
  18286. mesh._binaryInfo = parsedMesh._binaryInfo;
  18287. }
  18288. mesh._delayInfo = [];
  18289. if (parsedMesh.hasUVs) {
  18290. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18291. }
  18292. if (parsedMesh.hasUVs2) {
  18293. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18294. }
  18295. if (parsedMesh.hasUVs3) {
  18296. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18297. }
  18298. if (parsedMesh.hasUVs4) {
  18299. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18300. }
  18301. if (parsedMesh.hasUVs5) {
  18302. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18303. }
  18304. if (parsedMesh.hasUVs6) {
  18305. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18306. }
  18307. if (parsedMesh.hasColors) {
  18308. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18309. }
  18310. if (parsedMesh.hasMatricesIndices) {
  18311. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18312. }
  18313. if (parsedMesh.hasMatricesWeights) {
  18314. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18315. }
  18316. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18317. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18318. mesh._checkDelayState();
  18319. }
  18320. }
  18321. else {
  18322. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18323. }
  18324. // Material
  18325. if (parsedMesh.materialId) {
  18326. mesh.setMaterialByID(parsedMesh.materialId);
  18327. }
  18328. else {
  18329. mesh.material = null;
  18330. }
  18331. // Skeleton
  18332. if (parsedMesh.skeletonId > -1) {
  18333. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18334. if (parsedMesh.numBoneInfluencers) {
  18335. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18336. }
  18337. }
  18338. // Animations
  18339. if (parsedMesh.animations) {
  18340. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18341. var parsedAnimation = parsedMesh.animations[animationIndex];
  18342. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18343. }
  18344. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18345. }
  18346. if (parsedMesh.autoAnimate) {
  18347. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18348. }
  18349. // Layer Mask
  18350. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18351. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18352. }
  18353. else {
  18354. mesh.layerMask = 0x0FFFFFFF;
  18355. }
  18356. //(Deprecated) physics
  18357. if (parsedMesh.physicsImpostor) {
  18358. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18359. mass: parsedMesh.physicsMass,
  18360. friction: parsedMesh.physicsFriction,
  18361. restitution: parsedMesh.physicsRestitution
  18362. }, scene);
  18363. }
  18364. // Instances
  18365. if (parsedMesh.instances) {
  18366. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18367. var parsedInstance = parsedMesh.instances[index];
  18368. var instance = mesh.createInstance(parsedInstance.name);
  18369. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18370. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18371. if (parsedInstance.rotationQuaternion) {
  18372. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18373. }
  18374. else if (parsedInstance.rotation) {
  18375. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18376. }
  18377. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18378. instance.checkCollisions = mesh.checkCollisions;
  18379. if (parsedMesh.animations) {
  18380. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18381. parsedAnimation = parsedMesh.animations[animationIndex];
  18382. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18383. }
  18384. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18385. }
  18386. }
  18387. }
  18388. return mesh;
  18389. };
  18390. /**
  18391. * Creates a ribbon mesh.
  18392. * Please consider using the same method from the `MeshBuilder` class instead.
  18393. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18394. *
  18395. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18396. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18397. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18398. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18399. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  18400. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  18401. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  18402. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18403. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18405. */
  18406. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18407. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18408. pathArray: pathArray,
  18409. closeArray: closeArray,
  18410. closePath: closePath,
  18411. offset: offset,
  18412. updatable: updatable,
  18413. sideOrientation: sideOrientation,
  18414. instance: instance
  18415. }, scene);
  18416. };
  18417. /**
  18418. * Creates a plane polygonal mesh. By default, this is a disc.
  18419. * Please consider using the same method from the `MeshBuilder` class instead.
  18420. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18421. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  18422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18423. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18425. */
  18426. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18427. var options = {
  18428. radius: radius,
  18429. tessellation: tessellation,
  18430. sideOrientation: sideOrientation,
  18431. updatable: updatable
  18432. };
  18433. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18434. };
  18435. /**
  18436. * Creates a box mesh.
  18437. * Please consider using the same method from the `MeshBuilder` class instead.
  18438. * The parameter `size` sets the size (float) of each box side (default 1).
  18439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18442. */
  18443. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18444. var options = {
  18445. size: size,
  18446. sideOrientation: sideOrientation,
  18447. updatable: updatable
  18448. };
  18449. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18450. };
  18451. /**
  18452. * Creates a sphere mesh.
  18453. * Please consider using the same method from the `MeshBuilder` class instead.
  18454. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18455. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18456. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18457. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18459. */
  18460. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18461. var options = {
  18462. segments: segments,
  18463. diameterX: diameter,
  18464. diameterY: diameter,
  18465. diameterZ: diameter,
  18466. sideOrientation: sideOrientation,
  18467. updatable: updatable
  18468. };
  18469. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18470. };
  18471. /**
  18472. * Creates a cylinder or a cone mesh.
  18473. * Please consider using the same method from the `MeshBuilder` class instead.
  18474. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18475. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18476. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  18477. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18478. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18479. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18480. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18482. */
  18483. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18484. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18485. if (scene !== undefined) {
  18486. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18487. updatable = scene;
  18488. }
  18489. scene = subdivisions;
  18490. subdivisions = 1;
  18491. }
  18492. var options = {
  18493. height: height,
  18494. diameterTop: diameterTop,
  18495. diameterBottom: diameterBottom,
  18496. tessellation: tessellation,
  18497. subdivisions: subdivisions,
  18498. sideOrientation: sideOrientation,
  18499. updatable: updatable
  18500. };
  18501. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18502. };
  18503. // Torus (Code from SharpDX.org)
  18504. /**
  18505. * Creates a torus mesh.
  18506. * Please consider using the same method from the `MeshBuilder` class instead.
  18507. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18508. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18509. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18511. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18513. */
  18514. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18515. var options = {
  18516. diameter: diameter,
  18517. thickness: thickness,
  18518. tessellation: tessellation,
  18519. sideOrientation: sideOrientation,
  18520. updatable: updatable
  18521. };
  18522. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18523. };
  18524. /**
  18525. * Creates a torus knot mesh.
  18526. * Please consider using the same method from the `MeshBuilder` class instead.
  18527. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18528. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18529. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18530. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18531. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18532. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18534. */
  18535. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18536. var options = {
  18537. radius: radius,
  18538. tube: tube,
  18539. radialSegments: radialSegments,
  18540. tubularSegments: tubularSegments,
  18541. p: p,
  18542. q: q,
  18543. sideOrientation: sideOrientation,
  18544. updatable: updatable
  18545. };
  18546. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18547. };
  18548. /**
  18549. * Creates a line mesh.
  18550. * Please consider using the same method from the `MeshBuilder` class instead.
  18551. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18552. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18553. * The parameter `points` is an array successive Vector3.
  18554. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18555. * When updating an instance, remember that only point positions can change, not the number of points.
  18556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18557. */
  18558. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18559. var options = {
  18560. points: points,
  18561. updatable: updatable,
  18562. instance: instance
  18563. };
  18564. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18565. };
  18566. /**
  18567. * Creates a dashed line mesh.
  18568. * Please consider using the same method from the `MeshBuilder` class instead.
  18569. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18570. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18571. * The parameter `points` is an array successive Vector3.
  18572. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18573. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18574. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18575. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18576. * When updating an instance, remember that only point positions can change, not the number of points.
  18577. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18578. */
  18579. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18580. var options = {
  18581. points: points,
  18582. dashSize: dashSize,
  18583. gapSize: gapSize,
  18584. dashNb: dashNb,
  18585. updatable: updatable
  18586. };
  18587. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18588. };
  18589. /**
  18590. * Creates an extruded shape mesh.
  18591. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18592. * Please consider using the same method from the `MeshBuilder` class instead.
  18593. *
  18594. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18595. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18596. * extruded along the Z axis.
  18597. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18598. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  18599. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18600. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18601. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18602. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18603. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18604. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18606. */
  18607. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18608. var options = {
  18609. shape: shape,
  18610. path: path,
  18611. scale: scale,
  18612. rotation: rotation,
  18613. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18614. sideOrientation: sideOrientation,
  18615. instance: instance,
  18616. updatable: updatable
  18617. };
  18618. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18619. };
  18620. /**
  18621. * Creates an custom extruded shape mesh.
  18622. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18623. * Please consider using the same method from the `MeshBuilder` class instead.
  18624. *
  18625. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18626. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18627. * extruded along the Z axis.
  18628. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18629. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18630. * and the distance of this point from the begining of the path :
  18631. * ```rotationFunction = function(i, distance) {
  18632. * // do things
  18633. * return rotationValue; }```
  18634. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18635. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18636. * and the distance of this point from the begining of the path :
  18637. * ````scaleFunction = function(i, distance) {
  18638. * // do things
  18639. * return scaleValue;}```
  18640. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18641. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18642. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18643. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18644. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18645. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18647. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18649. */
  18650. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18651. var options = {
  18652. shape: shape,
  18653. path: path,
  18654. scaleFunction: scaleFunction,
  18655. rotationFunction: rotationFunction,
  18656. ribbonCloseArray: ribbonCloseArray,
  18657. ribbonClosePath: ribbonClosePath,
  18658. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18659. sideOrientation: sideOrientation,
  18660. instance: instance,
  18661. updatable: updatable
  18662. };
  18663. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18664. };
  18665. /**
  18666. * Creates lathe mesh.
  18667. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18668. * Please consider using the same method from the `MeshBuilder` class instead.
  18669. *
  18670. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  18671. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18672. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18673. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  18674. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18675. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18677. */
  18678. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18679. var options = {
  18680. shape: shape,
  18681. radius: radius,
  18682. tessellation: tessellation,
  18683. sideOrientation: sideOrientation,
  18684. updatable: updatable
  18685. };
  18686. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18687. };
  18688. /**
  18689. * Creates a plane mesh.
  18690. * Please consider using the same method from the `MeshBuilder` class instead.
  18691. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18693. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18695. */
  18696. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18697. var options = {
  18698. size: size,
  18699. width: size,
  18700. height: size,
  18701. sideOrientation: sideOrientation,
  18702. updatable: updatable
  18703. };
  18704. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18705. };
  18706. /**
  18707. * Creates a ground mesh.
  18708. * Please consider using the same method from the `MeshBuilder` class instead.
  18709. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18710. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18712. */
  18713. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18714. var options = {
  18715. width: width,
  18716. height: height,
  18717. subdivisions: subdivisions,
  18718. updatable: updatable
  18719. };
  18720. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18721. };
  18722. /**
  18723. * Creates a tiled ground mesh.
  18724. * Please consider using the same method from the `MeshBuilder` class instead.
  18725. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18726. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18727. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18728. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18729. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18730. * numbers of subdivisions on the ground width and height of each tile.
  18731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18732. */
  18733. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18734. var options = {
  18735. xmin: xmin,
  18736. zmin: zmin,
  18737. xmax: xmax,
  18738. zmax: zmax,
  18739. subdivisions: subdivisions,
  18740. precision: precision,
  18741. updatable: updatable
  18742. };
  18743. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18744. };
  18745. /**
  18746. * Creates a ground mesh from a height map.
  18747. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18748. * Please consider using the same method from the `MeshBuilder` class instead.
  18749. * The parameter `url` sets the URL of the height map image resource.
  18750. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18751. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18752. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18753. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18754. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  18755. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18756. * return; }```
  18757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18758. */
  18759. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18760. var options = {
  18761. width: width,
  18762. height: height,
  18763. subdivisions: subdivisions,
  18764. minHeight: minHeight,
  18765. maxHeight: maxHeight,
  18766. updatable: updatable,
  18767. onReady: onReady
  18768. };
  18769. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18770. };
  18771. /**
  18772. * Creates a tube mesh.
  18773. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18774. *
  18775. * Please consider using the same method from the `MeshBuilder` class instead.
  18776. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18777. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18778. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18779. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18780. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  18781. * It must return a radius value (positive float) :
  18782. * ```var radiusFunction = function(i, distance) {
  18783. * // do things
  18784. * return radius; }```
  18785. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18786. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  18787. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18788. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18789. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18790. */
  18791. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18792. var options = {
  18793. path: path,
  18794. radius: radius,
  18795. tessellation: tessellation,
  18796. radiusFunction: radiusFunction,
  18797. arc: 1,
  18798. cap: cap,
  18799. updatable: updatable,
  18800. sideOrientation: sideOrientation,
  18801. instance: instance
  18802. };
  18803. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18804. };
  18805. /**
  18806. * Creates a polyhedron mesh.
  18807. *
  18808. * Please consider using the same method from the `MeshBuilder` class instead.
  18809. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  18810. * to choose the wanted type.
  18811. * The parameter `size` (positive float, default 1) sets the polygon size.
  18812. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  18813. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  18814. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  18815. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  18816. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  18817. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  18818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18819. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18821. */
  18822. Mesh.CreatePolyhedron = function (name, options, scene) {
  18823. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  18824. };
  18825. /**
  18826. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18827. * Please consider using the same method from the `MeshBuilder` class instead.
  18828. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18829. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  18830. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18831. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  18832. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18833. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18835. */
  18836. Mesh.CreateIcoSphere = function (name, options, scene) {
  18837. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  18838. };
  18839. /**
  18840. * Creates a decal mesh.
  18841. * Please consider using the same method from the `MeshBuilder` class instead.
  18842. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  18843. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  18844. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  18845. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  18846. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  18847. */
  18848. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  18849. var options = {
  18850. position: position,
  18851. normal: normal,
  18852. size: size,
  18853. angle: angle
  18854. };
  18855. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  18856. };
  18857. // Skeletons
  18858. /**
  18859. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18860. */
  18861. Mesh.prototype.setPositionsForCPUSkinning = function () {
  18862. var source;
  18863. if (!this._sourcePositions) {
  18864. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18865. this._sourcePositions = new Float32Array(source);
  18866. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  18867. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  18868. }
  18869. }
  18870. return this._sourcePositions;
  18871. };
  18872. /**
  18873. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18874. */
  18875. Mesh.prototype.setNormalsForCPUSkinning = function () {
  18876. var source;
  18877. if (!this._sourceNormals) {
  18878. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18879. this._sourceNormals = new Float32Array(source);
  18880. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  18881. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  18882. }
  18883. }
  18884. return this._sourceNormals;
  18885. };
  18886. /**
  18887. * Update the vertex buffers by applying transformation from the bones
  18888. * @param {skeleton} skeleton to apply
  18889. */
  18890. Mesh.prototype.applySkeleton = function (skeleton) {
  18891. if (!this.geometry) {
  18892. return;
  18893. }
  18894. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  18895. return;
  18896. }
  18897. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  18898. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18899. return this;
  18900. }
  18901. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18902. return this;
  18903. }
  18904. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18905. return this;
  18906. }
  18907. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18908. return this;
  18909. }
  18910. if (!this._sourcePositions) {
  18911. this.setPositionsForCPUSkinning();
  18912. }
  18913. if (!this._sourceNormals) {
  18914. this.setNormalsForCPUSkinning();
  18915. }
  18916. // positionsData checks for not being Float32Array will only pass at most once
  18917. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18918. if (!(positionsData instanceof Float32Array)) {
  18919. positionsData = new Float32Array(positionsData);
  18920. }
  18921. // normalsData checks for not being Float32Array will only pass at most once
  18922. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18923. if (!(normalsData instanceof Float32Array)) {
  18924. normalsData = new Float32Array(normalsData);
  18925. }
  18926. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18927. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18928. var needExtras = this.numBoneInfluencers > 4;
  18929. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  18930. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  18931. var skeletonMatrices = skeleton.getTransformMatrices(this);
  18932. var tempVector3 = BABYLON.Vector3.Zero();
  18933. var finalMatrix = new BABYLON.Matrix();
  18934. var tempMatrix = new BABYLON.Matrix();
  18935. var matWeightIdx = 0;
  18936. var inf;
  18937. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  18938. var weight;
  18939. for (inf = 0; inf < 4; inf++) {
  18940. weight = matricesWeightsData[matWeightIdx + inf];
  18941. if (weight > 0) {
  18942. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18943. finalMatrix.addToSelf(tempMatrix);
  18944. }
  18945. else
  18946. break;
  18947. }
  18948. if (needExtras) {
  18949. for (inf = 0; inf < 4; inf++) {
  18950. weight = matricesWeightsExtraData[matWeightIdx + inf];
  18951. if (weight > 0) {
  18952. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18953. finalMatrix.addToSelf(tempMatrix);
  18954. }
  18955. else
  18956. break;
  18957. }
  18958. }
  18959. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  18960. tempVector3.toArray(positionsData, index);
  18961. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  18962. tempVector3.toArray(normalsData, index);
  18963. finalMatrix.reset();
  18964. }
  18965. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  18966. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  18967. return this;
  18968. };
  18969. // Tools
  18970. /**
  18971. * Returns an object `{min: Vector3, max: Vector3}`
  18972. * This min and max `Vector3` are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  18973. */
  18974. Mesh.MinMax = function (meshes) {
  18975. var minVector = null;
  18976. var maxVector = null;
  18977. for (var i in meshes) {
  18978. var mesh = meshes[i];
  18979. var boundingBox = mesh.getBoundingInfo().boundingBox;
  18980. if (!minVector) {
  18981. minVector = boundingBox.minimumWorld;
  18982. maxVector = boundingBox.maximumWorld;
  18983. continue;
  18984. }
  18985. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  18986. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  18987. }
  18988. return {
  18989. min: minVector,
  18990. max: maxVector
  18991. };
  18992. };
  18993. /**
  18994. * Returns a `Vector3`, the center of the `{min: Vector3, max: Vector3}` or the center of MinMax vector3 computed from a mesh array.
  18995. */
  18996. Mesh.Center = function (meshesOrMinMaxVector) {
  18997. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  18998. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  18999. };
  19000. /**
  19001. * Merge the array of meshes into a single mesh for performance reasons.
  19002. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  19003. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  19004. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  19005. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  19006. */
  19007. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  19008. if (disposeSource === void 0) { disposeSource = true; }
  19009. var index;
  19010. if (!allow32BitsIndices) {
  19011. var totalVertices = 0;
  19012. // Counting vertices
  19013. for (index = 0; index < meshes.length; index++) {
  19014. if (meshes[index]) {
  19015. totalVertices += meshes[index].getTotalVertices();
  19016. if (totalVertices > 65536) {
  19017. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  19018. return null;
  19019. }
  19020. }
  19021. }
  19022. }
  19023. // Merge
  19024. var vertexData;
  19025. var otherVertexData;
  19026. var source;
  19027. for (index = 0; index < meshes.length; index++) {
  19028. if (meshes[index]) {
  19029. meshes[index].computeWorldMatrix(true);
  19030. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  19031. otherVertexData.transform(meshes[index].getWorldMatrix());
  19032. if (vertexData) {
  19033. vertexData.merge(otherVertexData);
  19034. }
  19035. else {
  19036. vertexData = otherVertexData;
  19037. source = meshes[index];
  19038. }
  19039. }
  19040. }
  19041. if (!meshSubclass) {
  19042. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  19043. }
  19044. vertexData.applyToMesh(meshSubclass);
  19045. // Setting properties
  19046. meshSubclass.material = source.material;
  19047. meshSubclass.checkCollisions = source.checkCollisions;
  19048. // Cleaning
  19049. if (disposeSource) {
  19050. for (index = 0; index < meshes.length; index++) {
  19051. if (meshes[index]) {
  19052. meshes[index].dispose();
  19053. }
  19054. }
  19055. }
  19056. return meshSubclass;
  19057. };
  19058. // Consts
  19059. Mesh._FRONTSIDE = 0;
  19060. Mesh._BACKSIDE = 1;
  19061. Mesh._DOUBLESIDE = 2;
  19062. Mesh._DEFAULTSIDE = 0;
  19063. Mesh._NO_CAP = 0;
  19064. Mesh._CAP_START = 1;
  19065. Mesh._CAP_END = 2;
  19066. Mesh._CAP_ALL = 3;
  19067. return Mesh;
  19068. })(BABYLON.AbstractMesh);
  19069. BABYLON.Mesh = Mesh;
  19070. })(BABYLON || (BABYLON = {}));
  19071. var BABYLON;
  19072. (function (BABYLON) {
  19073. var SubMesh = (function () {
  19074. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  19075. if (createBoundingBox === void 0) { createBoundingBox = true; }
  19076. this.materialIndex = materialIndex;
  19077. this.verticesStart = verticesStart;
  19078. this.verticesCount = verticesCount;
  19079. this.indexStart = indexStart;
  19080. this.indexCount = indexCount;
  19081. this._renderId = 0;
  19082. this._mesh = mesh;
  19083. this._renderingMesh = renderingMesh || mesh;
  19084. mesh.subMeshes.push(this);
  19085. this._trianglePlanes = [];
  19086. this._id = mesh.subMeshes.length - 1;
  19087. if (createBoundingBox) {
  19088. this.refreshBoundingInfo();
  19089. mesh.computeWorldMatrix(true);
  19090. }
  19091. }
  19092. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  19093. get: function () {
  19094. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  19095. },
  19096. enumerable: true,
  19097. configurable: true
  19098. });
  19099. SubMesh.prototype.getBoundingInfo = function () {
  19100. if (this.IsGlobal) {
  19101. return this._mesh.getBoundingInfo();
  19102. }
  19103. return this._boundingInfo;
  19104. };
  19105. SubMesh.prototype.getMesh = function () {
  19106. return this._mesh;
  19107. };
  19108. SubMesh.prototype.getRenderingMesh = function () {
  19109. return this._renderingMesh;
  19110. };
  19111. SubMesh.prototype.getMaterial = function () {
  19112. var rootMaterial = this._renderingMesh.material;
  19113. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  19114. var multiMaterial = rootMaterial;
  19115. return multiMaterial.getSubMaterial(this.materialIndex);
  19116. }
  19117. if (!rootMaterial) {
  19118. return this._mesh.getScene().defaultMaterial;
  19119. }
  19120. return rootMaterial;
  19121. };
  19122. // Methods
  19123. SubMesh.prototype.refreshBoundingInfo = function () {
  19124. this._lastColliderWorldVertices = null;
  19125. if (this.IsGlobal) {
  19126. return;
  19127. }
  19128. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19129. if (!data) {
  19130. this._boundingInfo = this._mesh._boundingInfo;
  19131. return;
  19132. }
  19133. var indices = this._renderingMesh.getIndices();
  19134. var extend;
  19135. //is this the only submesh?
  19136. if (this.indexStart === 0 && this.indexCount === indices.length) {
  19137. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  19138. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  19139. }
  19140. else {
  19141. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  19142. }
  19143. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19144. };
  19145. SubMesh.prototype._checkCollision = function (collider) {
  19146. return this.getBoundingInfo()._checkCollision(collider);
  19147. };
  19148. SubMesh.prototype.updateBoundingInfo = function (world) {
  19149. if (!this.getBoundingInfo()) {
  19150. this.refreshBoundingInfo();
  19151. }
  19152. this.getBoundingInfo().update(world);
  19153. };
  19154. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  19155. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  19156. };
  19157. SubMesh.prototype.render = function (enableAlphaMode) {
  19158. this._renderingMesh.render(this, enableAlphaMode);
  19159. };
  19160. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  19161. if (!this._linesIndexBuffer) {
  19162. var linesIndices = [];
  19163. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19164. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  19165. }
  19166. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  19167. this.linesIndexCount = linesIndices.length;
  19168. }
  19169. return this._linesIndexBuffer;
  19170. };
  19171. SubMesh.prototype.canIntersects = function (ray) {
  19172. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  19173. };
  19174. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19175. var intersectInfo = null;
  19176. // LineMesh first as it's also a Mesh...
  19177. if (this._mesh instanceof BABYLON.LinesMesh) {
  19178. var lineMesh = this._mesh;
  19179. // Line test
  19180. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19181. var p0 = positions[indices[index]];
  19182. var p1 = positions[indices[index + 1]];
  19183. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19184. if (length < 0) {
  19185. continue;
  19186. }
  19187. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19188. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19189. if (fastCheck) {
  19190. break;
  19191. }
  19192. }
  19193. }
  19194. }
  19195. else {
  19196. // Triangles test
  19197. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19198. var p0 = positions[indices[index]];
  19199. var p1 = positions[indices[index + 1]];
  19200. var p2 = positions[indices[index + 2]];
  19201. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19202. if (currentIntersectInfo) {
  19203. if (currentIntersectInfo.distance < 0) {
  19204. continue;
  19205. }
  19206. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19207. intersectInfo = currentIntersectInfo;
  19208. intersectInfo.faceId = index / 3;
  19209. if (fastCheck) {
  19210. break;
  19211. }
  19212. }
  19213. }
  19214. }
  19215. }
  19216. return intersectInfo;
  19217. };
  19218. // Clone
  19219. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19220. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19221. if (!this.IsGlobal) {
  19222. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19223. }
  19224. return result;
  19225. };
  19226. // Dispose
  19227. SubMesh.prototype.dispose = function () {
  19228. if (this._linesIndexBuffer) {
  19229. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19230. this._linesIndexBuffer = null;
  19231. }
  19232. // Remove from mesh
  19233. var index = this._mesh.subMeshes.indexOf(this);
  19234. this._mesh.subMeshes.splice(index, 1);
  19235. };
  19236. // Statics
  19237. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19238. var minVertexIndex = Number.MAX_VALUE;
  19239. var maxVertexIndex = -Number.MAX_VALUE;
  19240. renderingMesh = renderingMesh || mesh;
  19241. var indices = renderingMesh.getIndices();
  19242. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19243. var vertexIndex = indices[index];
  19244. if (vertexIndex < minVertexIndex)
  19245. minVertexIndex = vertexIndex;
  19246. if (vertexIndex > maxVertexIndex)
  19247. maxVertexIndex = vertexIndex;
  19248. }
  19249. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19250. };
  19251. return SubMesh;
  19252. })();
  19253. BABYLON.SubMesh = SubMesh;
  19254. })(BABYLON || (BABYLON = {}));
  19255. var BABYLON;
  19256. (function (BABYLON) {
  19257. var MeshBuilder = (function () {
  19258. function MeshBuilder() {
  19259. }
  19260. /**
  19261. * Creates a box mesh.
  19262. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19263. * The parameter `size` sets the size (float) of each box side (default 1).
  19264. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19265. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 `Color3` elements) and `faceUV` (an array of 6 `Vector4` elements).
  19266. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19267. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19268. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19270. */
  19271. MeshBuilder.CreateBox = function (name, options, scene) {
  19272. var box = new BABYLON.Mesh(name, scene);
  19273. var vertexData = BABYLON.VertexData.CreateBox(options);
  19274. vertexData.applyToMesh(box, options.updatable);
  19275. return box;
  19276. };
  19277. /**
  19278. * Creates a sphere mesh.
  19279. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19280. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19281. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  19282. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19283. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  19284. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  19285. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19286. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19288. */
  19289. MeshBuilder.CreateSphere = function (name, options, scene) {
  19290. var sphere = new BABYLON.Mesh(name, scene);
  19291. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19292. vertexData.applyToMesh(sphere, options.updatable);
  19293. return sphere;
  19294. };
  19295. /**
  19296. * Creates a plane polygonal mesh. By default, this is a disc.
  19297. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19298. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19299. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  19300. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  19301. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19302. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19304. */
  19305. MeshBuilder.CreateDisc = function (name, options, scene) {
  19306. var disc = new BABYLON.Mesh(name, scene);
  19307. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19308. vertexData.applyToMesh(disc, options.updatable);
  19309. return disc;
  19310. };
  19311. /**
  19312. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19313. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19314. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19315. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  19316. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19317. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  19318. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19319. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19321. */
  19322. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19323. var sphere = new BABYLON.Mesh(name, scene);
  19324. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19325. vertexData.applyToMesh(sphere, options.updatable);
  19326. return sphere;
  19327. };
  19328. ;
  19329. /**
  19330. * Creates a ribbon mesh.
  19331. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19332. *
  19333. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19334. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19335. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19336. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19337. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  19338. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  19339. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  19340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19341. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19343. */
  19344. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19345. var pathArray = options.pathArray;
  19346. var closeArray = options.closeArray;
  19347. var closePath = options.closePath;
  19348. var offset = options.offset;
  19349. var sideOrientation = options.sideOrientation;
  19350. var instance = options.instance;
  19351. var updatable = options.updatable;
  19352. if (instance) {
  19353. // positionFunction : ribbon case
  19354. // only pathArray and sideOrientation parameters are taken into account for positions update
  19355. var positionFunction = function (positions) {
  19356. var minlg = pathArray[0].length;
  19357. var i = 0;
  19358. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19359. for (var si = 1; si <= ns; si++) {
  19360. for (var p = 0; p < pathArray.length; p++) {
  19361. var path = pathArray[p];
  19362. var l = path.length;
  19363. minlg = (minlg < l) ? minlg : l;
  19364. var j = 0;
  19365. while (j < minlg) {
  19366. positions[i] = path[j].x;
  19367. positions[i + 1] = path[j].y;
  19368. positions[i + 2] = path[j].z;
  19369. j++;
  19370. i += 3;
  19371. }
  19372. if (instance._closePath) {
  19373. positions[i] = path[0].x;
  19374. positions[i + 1] = path[0].y;
  19375. positions[i + 2] = path[0].z;
  19376. i += 3;
  19377. }
  19378. }
  19379. }
  19380. };
  19381. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19382. positionFunction(positions);
  19383. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19384. if (!(instance.areNormalsFrozen)) {
  19385. var indices = instance.getIndices();
  19386. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19387. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19388. if (instance._closePath) {
  19389. var indexFirst = 0;
  19390. var indexLast = 0;
  19391. for (var p = 0; p < pathArray.length; p++) {
  19392. indexFirst = instance._idx[p] * 3;
  19393. if (p + 1 < pathArray.length) {
  19394. indexLast = (instance._idx[p + 1] - 1) * 3;
  19395. }
  19396. else {
  19397. indexLast = normals.length - 3;
  19398. }
  19399. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19400. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19401. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19402. normals[indexLast] = normals[indexFirst];
  19403. normals[indexLast + 1] = normals[indexFirst + 1];
  19404. normals[indexLast + 2] = normals[indexFirst + 2];
  19405. }
  19406. }
  19407. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19408. }
  19409. return instance;
  19410. }
  19411. else {
  19412. var ribbon = new BABYLON.Mesh(name, scene);
  19413. ribbon.sideOrientation = sideOrientation;
  19414. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19415. if (closePath) {
  19416. ribbon._idx = vertexData._idx;
  19417. }
  19418. ribbon._closePath = closePath;
  19419. ribbon._closeArray = closeArray;
  19420. vertexData.applyToMesh(ribbon, updatable);
  19421. return ribbon;
  19422. }
  19423. };
  19424. /**
  19425. * Creates a cylinder or a cone mesh.
  19426. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19427. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19428. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19429. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  19430. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19431. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19432. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19433. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19434. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19435. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n `Color3` elements) and `faceUV` (an array of n `Vector4` elements).
  19436. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  19437. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19438. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  19439. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  19440. * If `enclose` is false, a ring surface is one element.
  19441. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19442. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  19443. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19446. */
  19447. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19448. var cylinder = new BABYLON.Mesh(name, scene);
  19449. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19450. vertexData.applyToMesh(cylinder, options.updatable);
  19451. return cylinder;
  19452. };
  19453. /**
  19454. * Creates a torus mesh.
  19455. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19456. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19457. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19458. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19459. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19460. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19462. */
  19463. MeshBuilder.CreateTorus = function (name, options, scene) {
  19464. var torus = new BABYLON.Mesh(name, scene);
  19465. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19466. vertexData.applyToMesh(torus, options.updatable);
  19467. return torus;
  19468. };
  19469. /**
  19470. * Creates a torus knot mesh.
  19471. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19472. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19473. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19474. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19475. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19476. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19477. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19479. */
  19480. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19481. var torusKnot = new BABYLON.Mesh(name, scene);
  19482. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19483. vertexData.applyToMesh(torusKnot, options.updatable);
  19484. return torusKnot;
  19485. };
  19486. /**
  19487. * Creates a line system mesh.
  19488. * A line system is a pool of many lines gathered in a single mesh.
  19489. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19490. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  19491. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19492. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19493. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  19494. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19495. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19497. */
  19498. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19499. var instance = options.instance;
  19500. var lines = options.lines;
  19501. if (instance) {
  19502. var positionFunction = function (positions) {
  19503. var i = 0;
  19504. for (var l = 0; l < lines.length; l++) {
  19505. var points = lines[l];
  19506. for (var p = 0; p < points.length; p++) {
  19507. positions[i] = points[p].x;
  19508. positions[i + 1] = points[p].y;
  19509. positions[i + 2] = points[p].z;
  19510. i += 3;
  19511. }
  19512. }
  19513. };
  19514. instance.updateMeshPositions(positionFunction, false);
  19515. return instance;
  19516. }
  19517. // line system creation
  19518. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19519. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19520. vertexData.applyToMesh(lineSystem, options.updatable);
  19521. return lineSystem;
  19522. };
  19523. /**
  19524. * Creates a line mesh.
  19525. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19526. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  19527. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19528. * The parameter `points` is an array successive Vector3.
  19529. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19530. * When updating an instance, remember that only point positions can change, not the number of points.
  19531. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19532. */
  19533. MeshBuilder.CreateLines = function (name, options, scene) {
  19534. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19535. return lines;
  19536. };
  19537. /**
  19538. * Creates a dashed line mesh.
  19539. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19540. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  19541. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19542. * The parameter `points` is an array successive Vector3.
  19543. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19544. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19545. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19546. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19547. * When updating an instance, remember that only point positions can change, not the number of points.
  19548. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19549. */
  19550. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19551. var points = options.points;
  19552. var instance = options.instance;
  19553. var gapSize = options.gapSize;
  19554. var dashNb = options.dashNb;
  19555. var dashSize = options.dashSize;
  19556. if (instance) {
  19557. var positionFunction = function (positions) {
  19558. var curvect = BABYLON.Vector3.Zero();
  19559. var nbSeg = positions.length / 6;
  19560. var lg = 0;
  19561. var nb = 0;
  19562. var shft = 0;
  19563. var dashshft = 0;
  19564. var curshft = 0;
  19565. var p = 0;
  19566. var i = 0;
  19567. var j = 0;
  19568. for (i = 0; i < points.length - 1; i++) {
  19569. points[i + 1].subtractToRef(points[i], curvect);
  19570. lg += curvect.length();
  19571. }
  19572. shft = lg / nbSeg;
  19573. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19574. for (i = 0; i < points.length - 1; i++) {
  19575. points[i + 1].subtractToRef(points[i], curvect);
  19576. nb = Math.floor(curvect.length() / shft);
  19577. curvect.normalize();
  19578. j = 0;
  19579. while (j < nb && p < positions.length) {
  19580. curshft = shft * j;
  19581. positions[p] = points[i].x + curshft * curvect.x;
  19582. positions[p + 1] = points[i].y + curshft * curvect.y;
  19583. positions[p + 2] = points[i].z + curshft * curvect.z;
  19584. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19585. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19586. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19587. p += 6;
  19588. j++;
  19589. }
  19590. }
  19591. while (p < positions.length) {
  19592. positions[p] = points[i].x;
  19593. positions[p + 1] = points[i].y;
  19594. positions[p + 2] = points[i].z;
  19595. p += 3;
  19596. }
  19597. };
  19598. instance.updateMeshPositions(positionFunction, false);
  19599. return instance;
  19600. }
  19601. // dashed lines creation
  19602. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19603. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19604. vertexData.applyToMesh(dashedLines, options.updatable);
  19605. dashedLines.dashSize = dashSize;
  19606. dashedLines.gapSize = gapSize;
  19607. return dashedLines;
  19608. };
  19609. /**
  19610. * Creates an extruded shape mesh.
  19611. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19612. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19613. *
  19614. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19615. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  19616. * extruded along the Z axis.
  19617. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19618. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  19619. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19620. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19621. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19622. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19624. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19626. */
  19627. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19628. var path = options.path;
  19629. var shape = options.shape;
  19630. var scale = options.scale || 1;
  19631. var rotation = options.rotation || 0;
  19632. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19633. var updatable = options.updatable;
  19634. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19635. var instance = options.instance;
  19636. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19637. };
  19638. /**
  19639. * Creates an custom extruded shape mesh.
  19640. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19641. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19642. *
  19643. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19644. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  19645. * extruded along the Z axis.
  19646. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19647. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19648. * and the distance of this point from the begining of the path :
  19649. * ```rotationFunction = function(i, distance) {
  19650. * // do things
  19651. * return rotationValue; }```
  19652. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19653. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19654. * and the distance of this point from the begining of the path :
  19655. * ````scaleFunction = function(i, distance) {
  19656. * // do things
  19657. * return scaleValue;}```
  19658. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19659. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19660. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19661. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19662. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19663. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19664. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19665. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19667. */
  19668. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19669. var path = options.path;
  19670. var shape = options.shape;
  19671. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19672. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19673. var ribbonCloseArray = options.ribbonCloseArray || false;
  19674. var ribbonClosePath = options.ribbonClosePath || false;
  19675. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19676. var updatable = options.updatable;
  19677. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19678. var instance = options.instance;
  19679. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19680. };
  19681. /**
  19682. * Creates lathe mesh.
  19683. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19684. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19685. *
  19686. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  19687. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19688. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19689. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19690. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  19691. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19692. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19693. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19694. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19696. */
  19697. MeshBuilder.CreateLathe = function (name, options, scene) {
  19698. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19699. var closed = (options.closed === undefined) ? true : options.closed;
  19700. var shape = options.shape;
  19701. var radius = options.radius || 1;
  19702. var tessellation = options.tessellation || 64;
  19703. var updatable = options.updatable;
  19704. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19705. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19706. var pi2 = Math.PI * 2;
  19707. var paths = new Array();
  19708. var i = 0;
  19709. var p = 0;
  19710. var step = pi2 / tessellation * arc;
  19711. var rotated;
  19712. var path = new Array();
  19713. ;
  19714. for (i = 0; i <= tessellation; i++) {
  19715. var path = [];
  19716. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19717. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19718. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19719. }
  19720. for (p = 0; p < shape.length; p++) {
  19721. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19722. path.push(rotated);
  19723. }
  19724. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19725. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  19726. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19727. }
  19728. paths.push(path);
  19729. }
  19730. // lathe ribbon
  19731. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19732. return lathe;
  19733. };
  19734. /**
  19735. * Creates a plane mesh.
  19736. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19737. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19738. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19739. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19741. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19743. */
  19744. MeshBuilder.CreatePlane = function (name, options, scene) {
  19745. var plane = new BABYLON.Mesh(name, scene);
  19746. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19747. vertexData.applyToMesh(plane, options.updatable);
  19748. if (options.sourcePlane) {
  19749. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19750. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19751. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19752. plane.rotate(vectorProduct, product);
  19753. }
  19754. return plane;
  19755. };
  19756. /**
  19757. * Creates a ground mesh.
  19758. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19759. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19760. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19761. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19762. */
  19763. MeshBuilder.CreateGround = function (name, options, scene) {
  19764. var ground = new BABYLON.GroundMesh(name, scene);
  19765. ground._setReady(false);
  19766. ground._subdivisions = options.subdivisions || 1;
  19767. ground._width = options.width || 1;
  19768. ground._height = options.height || 1;
  19769. ground._maxX = ground._width / 2;
  19770. ground._maxZ = ground._height / 2;
  19771. ground._minX = -ground._maxX;
  19772. ground._minZ = -ground._maxZ;
  19773. var vertexData = BABYLON.VertexData.CreateGround(options);
  19774. vertexData.applyToMesh(ground, options.updatable);
  19775. ground._setReady(true);
  19776. return ground;
  19777. };
  19778. /**
  19779. * Creates a tiled ground mesh.
  19780. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19781. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19782. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19783. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19784. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19785. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19786. * numbers of subdivisions on the ground width and height of each tile.
  19787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19788. */
  19789. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19790. var tiledGround = new BABYLON.Mesh(name, scene);
  19791. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19792. vertexData.applyToMesh(tiledGround, options.updatable);
  19793. return tiledGround;
  19794. };
  19795. /**
  19796. * Creates a ground mesh from a height map.
  19797. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19798. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19799. * The parameter `url` sets the URL of the height map image resource.
  19800. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19801. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19802. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19803. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19804. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  19805. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19806. * return; }```
  19807. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19808. */
  19809. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  19810. var width = options.width || 10;
  19811. var height = options.height || 10;
  19812. var subdivisions = options.subdivisions || 1;
  19813. var minHeight = options.minHeight;
  19814. var maxHeight = options.maxHeight || 10;
  19815. var updatable = options.updatable;
  19816. var onReady = options.onReady;
  19817. var ground = new BABYLON.GroundMesh(name, scene);
  19818. ground._subdivisions = subdivisions;
  19819. ground._width = width;
  19820. ground._height = height;
  19821. ground._maxX = ground._width / 2;
  19822. ground._maxZ = ground._height / 2;
  19823. ground._minX = -ground._maxX;
  19824. ground._minZ = -ground._maxZ;
  19825. ground._setReady(false);
  19826. var onload = function (img) {
  19827. // Getting height map data
  19828. var canvas = document.createElement("canvas");
  19829. var context = canvas.getContext("2d");
  19830. var bufferWidth = img.width;
  19831. var bufferHeight = img.height;
  19832. canvas.width = bufferWidth;
  19833. canvas.height = bufferHeight;
  19834. context.drawImage(img, 0, 0);
  19835. // Create VertexData from map data
  19836. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19837. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  19838. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  19839. width: width, height: height,
  19840. subdivisions: subdivisions,
  19841. minHeight: minHeight, maxHeight: maxHeight,
  19842. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  19843. });
  19844. vertexData.applyToMesh(ground, updatable);
  19845. ground._setReady(true);
  19846. //execute ready callback, if set
  19847. if (onReady) {
  19848. onReady(ground);
  19849. }
  19850. };
  19851. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19852. return ground;
  19853. };
  19854. /**
  19855. * Creates a tube mesh.
  19856. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19857. *
  19858. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  19859. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19860. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19861. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19862. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19863. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  19864. * It must return a radius value (positive float) :
  19865. * ```var radiusFunction = function(i, distance) {
  19866. * // do things
  19867. * return radius; }```
  19868. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  19869. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19870. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  19871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19872. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19874. */
  19875. MeshBuilder.CreateTube = function (name, options, scene) {
  19876. var path = options.path;
  19877. var radius = options.radius || 1;
  19878. var tessellation = options.tessellation || 64;
  19879. var radiusFunction = options.radiusFunction;
  19880. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19881. var updatable = options.updatable;
  19882. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19883. var instance = options.instance;
  19884. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  19885. // tube geometry
  19886. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  19887. var tangents = path3D.getTangents();
  19888. var normals = path3D.getNormals();
  19889. var distances = path3D.getDistances();
  19890. var pi2 = Math.PI * 2;
  19891. var step = pi2 / tessellation * arc;
  19892. var returnRadius = function () { return radius; };
  19893. var radiusFunctionFinal = radiusFunction || returnRadius;
  19894. var circlePath;
  19895. var rad;
  19896. var normal;
  19897. var rotated;
  19898. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19899. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19900. for (var i = 0; i < path.length; i++) {
  19901. rad = radiusFunctionFinal(i, distances[i]); // current radius
  19902. circlePath = Array(); // current circle array
  19903. normal = normals[i]; // current normal
  19904. for (var t = 0; t < tessellation; t++) {
  19905. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  19906. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  19907. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  19908. rotated.scaleInPlace(rad).addInPlace(path[i]);
  19909. circlePath[t] = rotated;
  19910. }
  19911. circlePaths[index] = circlePath;
  19912. index++;
  19913. }
  19914. // cap
  19915. var capPath = function (nbPoints, pathIndex) {
  19916. var pointCap = Array();
  19917. for (var i = 0; i < nbPoints; i++) {
  19918. pointCap.push(path[pathIndex]);
  19919. }
  19920. return pointCap;
  19921. };
  19922. switch (cap) {
  19923. case BABYLON.Mesh.NO_CAP:
  19924. break;
  19925. case BABYLON.Mesh.CAP_START:
  19926. circlePaths[0] = capPath(tessellation, 0);
  19927. circlePaths[1] = circlePaths[2].slice(0);
  19928. break;
  19929. case BABYLON.Mesh.CAP_END:
  19930. circlePaths[index] = circlePaths[index - 1].slice(0);
  19931. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19932. break;
  19933. case BABYLON.Mesh.CAP_ALL:
  19934. circlePaths[0] = capPath(tessellation, 0);
  19935. circlePaths[1] = circlePaths[2].slice(0);
  19936. circlePaths[index] = circlePaths[index - 1].slice(0);
  19937. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19938. break;
  19939. default:
  19940. break;
  19941. }
  19942. return circlePaths;
  19943. };
  19944. var path3D;
  19945. var pathArray;
  19946. if (instance) {
  19947. var arc = options.arc || instance.arc;
  19948. path3D = (instance.path3D).update(path);
  19949. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  19950. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  19951. instance.path3D = path3D;
  19952. instance.pathArray = pathArray;
  19953. instance.arc = arc;
  19954. return instance;
  19955. }
  19956. // tube creation
  19957. path3D = new BABYLON.Path3D(path);
  19958. var newPathArray = new Array();
  19959. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19960. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  19961. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  19962. tube.pathArray = pathArray;
  19963. tube.path3D = path3D;
  19964. tube.tessellation = tessellation;
  19965. tube.cap = cap;
  19966. tube.arc = options.arc;
  19967. return tube;
  19968. };
  19969. /**
  19970. * Creates a polyhedron mesh.
  19971. *
  19972. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  19973. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  19974. * to choose the wanted type.
  19975. * The parameter `size` (positive float, default 1) sets the polygon size.
  19976. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19977. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  19978. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  19979. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  19980. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19981. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  19982. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19983. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19984. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19985. */
  19986. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  19987. var polyhedron = new BABYLON.Mesh(name, scene);
  19988. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  19989. vertexData.applyToMesh(polyhedron, options.updatable);
  19990. return polyhedron;
  19991. };
  19992. /**
  19993. * Creates a decal mesh.
  19994. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  19995. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  19996. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19997. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19998. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19999. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20000. */
  20001. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  20002. var indices = sourceMesh.getIndices();
  20003. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20004. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20005. var position = options.position || BABYLON.Vector3.Zero();
  20006. var normal = options.normal || BABYLON.Vector3.Up();
  20007. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  20008. var angle = options.angle || 0;
  20009. // Getting correct rotation
  20010. if (!normal) {
  20011. var target = new BABYLON.Vector3(0, 0, 1);
  20012. var camera = sourceMesh.getScene().activeCamera;
  20013. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  20014. normal = camera.globalPosition.subtract(cameraWorldTarget);
  20015. }
  20016. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  20017. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  20018. var pitch = Math.atan2(normal.y, len);
  20019. // Matrix
  20020. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  20021. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  20022. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  20023. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  20024. var vertexData = new BABYLON.VertexData();
  20025. vertexData.indices = [];
  20026. vertexData.positions = [];
  20027. vertexData.normals = [];
  20028. vertexData.uvs = [];
  20029. var currentVertexDataIndex = 0;
  20030. var extractDecalVector3 = function (indexId) {
  20031. var vertexId = indices[indexId];
  20032. var result = new BABYLON.PositionNormalVertex();
  20033. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  20034. // Send vector to decal local world
  20035. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  20036. // Get normal
  20037. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  20038. return result;
  20039. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  20040. var clip = function (vertices, axis) {
  20041. if (vertices.length === 0) {
  20042. return vertices;
  20043. }
  20044. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  20045. var clipVertices = function (v0, v1) {
  20046. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  20047. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  20048. };
  20049. var result = new Array();
  20050. for (var index = 0; index < vertices.length; index += 3) {
  20051. var v1Out;
  20052. var v2Out;
  20053. var v3Out;
  20054. var total = 0;
  20055. var nV1, nV2, nV3, nV4;
  20056. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  20057. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  20058. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  20059. v1Out = d1 > 0;
  20060. v2Out = d2 > 0;
  20061. v3Out = d3 > 0;
  20062. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  20063. switch (total) {
  20064. case 0:
  20065. result.push(vertices[index]);
  20066. result.push(vertices[index + 1]);
  20067. result.push(vertices[index + 2]);
  20068. break;
  20069. case 1:
  20070. if (v1Out) {
  20071. nV1 = vertices[index + 1];
  20072. nV2 = vertices[index + 2];
  20073. nV3 = clipVertices(vertices[index], nV1);
  20074. nV4 = clipVertices(vertices[index], nV2);
  20075. }
  20076. if (v2Out) {
  20077. nV1 = vertices[index];
  20078. nV2 = vertices[index + 2];
  20079. nV3 = clipVertices(vertices[index + 1], nV1);
  20080. nV4 = clipVertices(vertices[index + 1], nV2);
  20081. result.push(nV3);
  20082. result.push(nV2.clone());
  20083. result.push(nV1.clone());
  20084. result.push(nV2.clone());
  20085. result.push(nV3.clone());
  20086. result.push(nV4);
  20087. break;
  20088. }
  20089. if (v3Out) {
  20090. nV1 = vertices[index];
  20091. nV2 = vertices[index + 1];
  20092. nV3 = clipVertices(vertices[index + 2], nV1);
  20093. nV4 = clipVertices(vertices[index + 2], nV2);
  20094. }
  20095. result.push(nV1.clone());
  20096. result.push(nV2.clone());
  20097. result.push(nV3);
  20098. result.push(nV4);
  20099. result.push(nV3.clone());
  20100. result.push(nV2.clone());
  20101. break;
  20102. case 2:
  20103. if (!v1Out) {
  20104. nV1 = vertices[index].clone();
  20105. nV2 = clipVertices(nV1, vertices[index + 1]);
  20106. nV3 = clipVertices(nV1, vertices[index + 2]);
  20107. result.push(nV1);
  20108. result.push(nV2);
  20109. result.push(nV3);
  20110. }
  20111. if (!v2Out) {
  20112. nV1 = vertices[index + 1].clone();
  20113. nV2 = clipVertices(nV1, vertices[index + 2]);
  20114. nV3 = clipVertices(nV1, vertices[index]);
  20115. result.push(nV1);
  20116. result.push(nV2);
  20117. result.push(nV3);
  20118. }
  20119. if (!v3Out) {
  20120. nV1 = vertices[index + 2].clone();
  20121. nV2 = clipVertices(nV1, vertices[index]);
  20122. nV3 = clipVertices(nV1, vertices[index + 1]);
  20123. result.push(nV1);
  20124. result.push(nV2);
  20125. result.push(nV3);
  20126. }
  20127. break;
  20128. case 3:
  20129. break;
  20130. }
  20131. }
  20132. return result;
  20133. };
  20134. for (var index = 0; index < indices.length; index += 3) {
  20135. var faceVertices = new Array();
  20136. faceVertices.push(extractDecalVector3(index));
  20137. faceVertices.push(extractDecalVector3(index + 1));
  20138. faceVertices.push(extractDecalVector3(index + 2));
  20139. // Clip
  20140. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  20141. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  20142. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  20143. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  20144. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  20145. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  20146. if (faceVertices.length === 0) {
  20147. continue;
  20148. }
  20149. // Add UVs and get back to world
  20150. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  20151. var vertex = faceVertices[vIndex];
  20152. //TODO check for Int32Array
  20153. vertexData.indices.push(currentVertexDataIndex);
  20154. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  20155. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  20156. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  20157. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  20158. currentVertexDataIndex++;
  20159. }
  20160. }
  20161. // Return mesh
  20162. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  20163. vertexData.applyToMesh(decal);
  20164. decal.position = position.clone();
  20165. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  20166. return decal;
  20167. };
  20168. // Privates
  20169. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  20170. // extrusion geometry
  20171. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  20172. var tangents = path3D.getTangents();
  20173. var normals = path3D.getNormals();
  20174. var binormals = path3D.getBinormals();
  20175. var distances = path3D.getDistances();
  20176. var angle = 0;
  20177. var returnScale = function () { return scale; };
  20178. var returnRotation = function () { return rotation; };
  20179. var rotate = custom ? rotateFunction : returnRotation;
  20180. var scl = custom ? scaleFunction : returnScale;
  20181. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20182. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20183. for (var i = 0; i < curve.length; i++) {
  20184. var shapePath = new Array();
  20185. var angleStep = rotate(i, distances[i]);
  20186. var scaleRatio = scl(i, distances[i]);
  20187. for (var p = 0; p < shape.length; p++) {
  20188. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20189. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20190. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20191. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20192. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20193. shapePath[p] = rotated;
  20194. }
  20195. shapePaths[index] = shapePath;
  20196. angle += angleStep;
  20197. index++;
  20198. }
  20199. // cap
  20200. var capPath = function (shapePath) {
  20201. var pointCap = Array();
  20202. var barycenter = BABYLON.Vector3.Zero();
  20203. var i;
  20204. for (i = 0; i < shapePath.length; i++) {
  20205. barycenter.addInPlace(shapePath[i]);
  20206. }
  20207. barycenter.scaleInPlace(1 / shapePath.length);
  20208. for (i = 0; i < shapePath.length; i++) {
  20209. pointCap.push(barycenter);
  20210. }
  20211. return pointCap;
  20212. };
  20213. switch (cap) {
  20214. case BABYLON.Mesh.NO_CAP:
  20215. break;
  20216. case BABYLON.Mesh.CAP_START:
  20217. shapePaths[0] = capPath(shapePaths[2]);
  20218. shapePaths[1] = shapePaths[2].slice(0);
  20219. break;
  20220. case BABYLON.Mesh.CAP_END:
  20221. shapePaths[index] = shapePaths[index - 1];
  20222. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20223. break;
  20224. case BABYLON.Mesh.CAP_ALL:
  20225. shapePaths[0] = capPath(shapePaths[2]);
  20226. shapePaths[1] = shapePaths[2].slice(0);
  20227. shapePaths[index] = shapePaths[index - 1];
  20228. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20229. break;
  20230. default:
  20231. break;
  20232. }
  20233. return shapePaths;
  20234. };
  20235. var path3D;
  20236. var pathArray;
  20237. if (instance) {
  20238. path3D = (instance.path3D).update(curve);
  20239. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20240. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20241. return instance;
  20242. }
  20243. // extruded shape creation
  20244. path3D = new BABYLON.Path3D(curve);
  20245. var newShapePaths = new Array();
  20246. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20247. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20248. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20249. extrudedGeneric.pathArray = pathArray;
  20250. extrudedGeneric.path3D = path3D;
  20251. extrudedGeneric.cap = cap;
  20252. return extrudedGeneric;
  20253. };
  20254. return MeshBuilder;
  20255. })();
  20256. BABYLON.MeshBuilder = MeshBuilder;
  20257. })(BABYLON || (BABYLON = {}));
  20258. var BABYLON;
  20259. (function (BABYLON) {
  20260. var BaseTexture = (function () {
  20261. function BaseTexture(scene) {
  20262. this.hasAlpha = false;
  20263. this.getAlphaFromRGB = false;
  20264. this.level = 1;
  20265. this.coordinatesIndex = 0;
  20266. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20267. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20268. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20269. this.anisotropicFilteringLevel = 4;
  20270. this.isCube = false;
  20271. this.isRenderTarget = false;
  20272. this.animations = new Array();
  20273. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20274. this._scene = scene;
  20275. this._scene.textures.push(this);
  20276. }
  20277. BaseTexture.prototype.getScene = function () {
  20278. return this._scene;
  20279. };
  20280. BaseTexture.prototype.getTextureMatrix = function () {
  20281. return null;
  20282. };
  20283. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20284. return null;
  20285. };
  20286. BaseTexture.prototype.getInternalTexture = function () {
  20287. return this._texture;
  20288. };
  20289. BaseTexture.prototype.isReady = function () {
  20290. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20291. return true;
  20292. }
  20293. if (this._texture) {
  20294. return this._texture.isReady;
  20295. }
  20296. return false;
  20297. };
  20298. BaseTexture.prototype.getSize = function () {
  20299. if (this._texture._width) {
  20300. return { width: this._texture._width, height: this._texture._height };
  20301. }
  20302. if (this._texture._size) {
  20303. return { width: this._texture._size, height: this._texture._size };
  20304. }
  20305. return { width: 0, height: 0 };
  20306. };
  20307. BaseTexture.prototype.getBaseSize = function () {
  20308. if (!this.isReady() || !this._texture)
  20309. return { width: 0, height: 0 };
  20310. if (this._texture._size) {
  20311. return { width: this._texture._size, height: this._texture._size };
  20312. }
  20313. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20314. };
  20315. BaseTexture.prototype.scale = function (ratio) {
  20316. };
  20317. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20318. get: function () {
  20319. return false;
  20320. },
  20321. enumerable: true,
  20322. configurable: true
  20323. });
  20324. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20325. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20326. for (var index = 0; index < texturesCache.length; index++) {
  20327. var texturesCacheEntry = texturesCache[index];
  20328. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20329. texturesCache.splice(index, 1);
  20330. return;
  20331. }
  20332. }
  20333. };
  20334. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20335. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20336. for (var index = 0; index < texturesCache.length; index++) {
  20337. var texturesCacheEntry = texturesCache[index];
  20338. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20339. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20340. texturesCacheEntry.references++;
  20341. return texturesCacheEntry;
  20342. }
  20343. }
  20344. }
  20345. return null;
  20346. };
  20347. BaseTexture.prototype.delayLoad = function () {
  20348. };
  20349. BaseTexture.prototype.clone = function () {
  20350. return null;
  20351. };
  20352. BaseTexture.prototype.releaseInternalTexture = function () {
  20353. if (this._texture) {
  20354. this._scene.getEngine().releaseInternalTexture(this._texture);
  20355. delete this._texture;
  20356. }
  20357. };
  20358. BaseTexture.prototype.dispose = function () {
  20359. // Animations
  20360. this.getScene().stopAnimation(this);
  20361. // Remove from scene
  20362. var index = this._scene.textures.indexOf(this);
  20363. if (index >= 0) {
  20364. this._scene.textures.splice(index, 1);
  20365. }
  20366. if (this._texture === undefined) {
  20367. return;
  20368. }
  20369. // Release
  20370. this.releaseInternalTexture();
  20371. // Callback
  20372. if (this.onDispose) {
  20373. this.onDispose();
  20374. }
  20375. };
  20376. BaseTexture.prototype.serialize = function () {
  20377. if (!this.name) {
  20378. return null;
  20379. }
  20380. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20381. // Animations
  20382. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20383. return serializationObject;
  20384. };
  20385. __decorate([
  20386. BABYLON.serialize()
  20387. ], BaseTexture.prototype, "name", void 0);
  20388. __decorate([
  20389. BABYLON.serialize()
  20390. ], BaseTexture.prototype, "hasAlpha", void 0);
  20391. __decorate([
  20392. BABYLON.serialize()
  20393. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20394. __decorate([
  20395. BABYLON.serialize()
  20396. ], BaseTexture.prototype, "level", void 0);
  20397. __decorate([
  20398. BABYLON.serialize()
  20399. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20400. __decorate([
  20401. BABYLON.serialize()
  20402. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20403. __decorate([
  20404. BABYLON.serialize()
  20405. ], BaseTexture.prototype, "wrapU", void 0);
  20406. __decorate([
  20407. BABYLON.serialize()
  20408. ], BaseTexture.prototype, "wrapV", void 0);
  20409. __decorate([
  20410. BABYLON.serialize()
  20411. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20412. __decorate([
  20413. BABYLON.serialize()
  20414. ], BaseTexture.prototype, "isCube", void 0);
  20415. __decorate([
  20416. BABYLON.serialize()
  20417. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20418. return BaseTexture;
  20419. })();
  20420. BABYLON.BaseTexture = BaseTexture;
  20421. })(BABYLON || (BABYLON = {}));
  20422. var BABYLON;
  20423. (function (BABYLON) {
  20424. var Texture = (function (_super) {
  20425. __extends(Texture, _super);
  20426. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20427. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20428. if (onLoad === void 0) { onLoad = null; }
  20429. if (onError === void 0) { onError = null; }
  20430. if (buffer === void 0) { buffer = null; }
  20431. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20432. _super.call(this, scene);
  20433. this.uOffset = 0;
  20434. this.vOffset = 0;
  20435. this.uScale = 1.0;
  20436. this.vScale = 1.0;
  20437. this.uAng = 0;
  20438. this.vAng = 0;
  20439. this.wAng = 0;
  20440. this.name = url;
  20441. this.url = url;
  20442. this._noMipmap = noMipmap;
  20443. this._invertY = invertY;
  20444. this._samplingMode = samplingMode;
  20445. this._buffer = buffer;
  20446. this._deleteBuffer = deleteBuffer;
  20447. if (!url) {
  20448. return;
  20449. }
  20450. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20451. if (!this._texture) {
  20452. if (!scene.useDelayedTextureLoading) {
  20453. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20454. if (deleteBuffer) {
  20455. delete this._buffer;
  20456. }
  20457. }
  20458. else {
  20459. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20460. this._delayedOnLoad = onLoad;
  20461. this._delayedOnError = onError;
  20462. }
  20463. }
  20464. else {
  20465. BABYLON.Tools.SetImmediate(function () {
  20466. if (onLoad) {
  20467. onLoad();
  20468. }
  20469. });
  20470. }
  20471. }
  20472. Texture.prototype.delayLoad = function () {
  20473. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20474. return;
  20475. }
  20476. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20477. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20478. if (!this._texture) {
  20479. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20480. if (this._deleteBuffer) {
  20481. delete this._buffer;
  20482. }
  20483. }
  20484. };
  20485. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20486. if (!this._texture) {
  20487. return;
  20488. }
  20489. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20490. };
  20491. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20492. x *= this.uScale;
  20493. y *= this.vScale;
  20494. x -= 0.5 * this.uScale;
  20495. y -= 0.5 * this.vScale;
  20496. z -= 0.5;
  20497. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20498. t.x += 0.5 * this.uScale + this.uOffset;
  20499. t.y += 0.5 * this.vScale + this.vOffset;
  20500. t.z += 0.5;
  20501. };
  20502. Texture.prototype.getTextureMatrix = function () {
  20503. if (this.uOffset === this._cachedUOffset &&
  20504. this.vOffset === this._cachedVOffset &&
  20505. this.uScale === this._cachedUScale &&
  20506. this.vScale === this._cachedVScale &&
  20507. this.uAng === this._cachedUAng &&
  20508. this.vAng === this._cachedVAng &&
  20509. this.wAng === this._cachedWAng) {
  20510. return this._cachedTextureMatrix;
  20511. }
  20512. this._cachedUOffset = this.uOffset;
  20513. this._cachedVOffset = this.vOffset;
  20514. this._cachedUScale = this.uScale;
  20515. this._cachedVScale = this.vScale;
  20516. this._cachedUAng = this.uAng;
  20517. this._cachedVAng = this.vAng;
  20518. this._cachedWAng = this.wAng;
  20519. if (!this._cachedTextureMatrix) {
  20520. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20521. this._rowGenerationMatrix = new BABYLON.Matrix();
  20522. this._t0 = BABYLON.Vector3.Zero();
  20523. this._t1 = BABYLON.Vector3.Zero();
  20524. this._t2 = BABYLON.Vector3.Zero();
  20525. }
  20526. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20527. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20528. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20529. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20530. this._t1.subtractInPlace(this._t0);
  20531. this._t2.subtractInPlace(this._t0);
  20532. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20533. this._cachedTextureMatrix.m[0] = this._t1.x;
  20534. this._cachedTextureMatrix.m[1] = this._t1.y;
  20535. this._cachedTextureMatrix.m[2] = this._t1.z;
  20536. this._cachedTextureMatrix.m[4] = this._t2.x;
  20537. this._cachedTextureMatrix.m[5] = this._t2.y;
  20538. this._cachedTextureMatrix.m[6] = this._t2.z;
  20539. this._cachedTextureMatrix.m[8] = this._t0.x;
  20540. this._cachedTextureMatrix.m[9] = this._t0.y;
  20541. this._cachedTextureMatrix.m[10] = this._t0.z;
  20542. return this._cachedTextureMatrix;
  20543. };
  20544. Texture.prototype.getReflectionTextureMatrix = function () {
  20545. if (this.uOffset === this._cachedUOffset &&
  20546. this.vOffset === this._cachedVOffset &&
  20547. this.uScale === this._cachedUScale &&
  20548. this.vScale === this._cachedVScale &&
  20549. this.coordinatesMode === this._cachedCoordinatesMode) {
  20550. return this._cachedTextureMatrix;
  20551. }
  20552. if (!this._cachedTextureMatrix) {
  20553. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20554. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20555. }
  20556. this._cachedCoordinatesMode = this.coordinatesMode;
  20557. switch (this.coordinatesMode) {
  20558. case Texture.PLANAR_MODE:
  20559. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20560. this._cachedTextureMatrix[0] = this.uScale;
  20561. this._cachedTextureMatrix[5] = this.vScale;
  20562. this._cachedTextureMatrix[12] = this.uOffset;
  20563. this._cachedTextureMatrix[13] = this.vOffset;
  20564. break;
  20565. case Texture.PROJECTION_MODE:
  20566. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20567. this._projectionModeMatrix.m[0] = 0.5;
  20568. this._projectionModeMatrix.m[5] = -0.5;
  20569. this._projectionModeMatrix.m[10] = 0.0;
  20570. this._projectionModeMatrix.m[12] = 0.5;
  20571. this._projectionModeMatrix.m[13] = 0.5;
  20572. this._projectionModeMatrix.m[14] = 1.0;
  20573. this._projectionModeMatrix.m[15] = 1.0;
  20574. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20575. break;
  20576. default:
  20577. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20578. break;
  20579. }
  20580. return this._cachedTextureMatrix;
  20581. };
  20582. Texture.prototype.clone = function () {
  20583. var _this = this;
  20584. return BABYLON.SerializationHelper.Clone(function () {
  20585. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20586. }, this);
  20587. };
  20588. // Statics
  20589. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20590. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20591. if (onLoad === void 0) { onLoad = null; }
  20592. if (onError === void 0) { onError = null; }
  20593. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20594. };
  20595. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20596. if (parsedTexture.isCube) {
  20597. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20598. }
  20599. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20600. return null;
  20601. }
  20602. var texture = BABYLON.SerializationHelper.Parse(function () {
  20603. if (parsedTexture.mirrorPlane) {
  20604. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20605. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20606. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20607. return mirrorTexture;
  20608. }
  20609. else if (parsedTexture.isRenderTarget) {
  20610. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20611. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20612. return renderTargetTexture;
  20613. }
  20614. else {
  20615. var texture;
  20616. if (parsedTexture.base64String) {
  20617. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20618. }
  20619. else {
  20620. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20621. }
  20622. return texture;
  20623. }
  20624. }, parsedTexture, scene);
  20625. // Animations
  20626. if (parsedTexture.animations) {
  20627. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20628. var parsedAnimation = parsedTexture.animations[animationIndex];
  20629. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20630. }
  20631. }
  20632. return texture;
  20633. };
  20634. // Constants
  20635. Texture.NEAREST_SAMPLINGMODE = 1;
  20636. Texture.BILINEAR_SAMPLINGMODE = 2;
  20637. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20638. Texture.EXPLICIT_MODE = 0;
  20639. Texture.SPHERICAL_MODE = 1;
  20640. Texture.PLANAR_MODE = 2;
  20641. Texture.CUBIC_MODE = 3;
  20642. Texture.PROJECTION_MODE = 4;
  20643. Texture.SKYBOX_MODE = 5;
  20644. Texture.INVCUBIC_MODE = 6;
  20645. Texture.EQUIRECTANGULAR_MODE = 7;
  20646. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20647. Texture.CLAMP_ADDRESSMODE = 0;
  20648. Texture.WRAP_ADDRESSMODE = 1;
  20649. Texture.MIRROR_ADDRESSMODE = 2;
  20650. __decorate([
  20651. BABYLON.serialize()
  20652. ], Texture.prototype, "url", void 0);
  20653. __decorate([
  20654. BABYLON.serialize()
  20655. ], Texture.prototype, "uOffset", void 0);
  20656. __decorate([
  20657. BABYLON.serialize()
  20658. ], Texture.prototype, "vOffset", void 0);
  20659. __decorate([
  20660. BABYLON.serialize()
  20661. ], Texture.prototype, "uScale", void 0);
  20662. __decorate([
  20663. BABYLON.serialize()
  20664. ], Texture.prototype, "vScale", void 0);
  20665. __decorate([
  20666. BABYLON.serialize()
  20667. ], Texture.prototype, "uAng", void 0);
  20668. __decorate([
  20669. BABYLON.serialize()
  20670. ], Texture.prototype, "vAng", void 0);
  20671. __decorate([
  20672. BABYLON.serialize()
  20673. ], Texture.prototype, "wAng", void 0);
  20674. return Texture;
  20675. })(BABYLON.BaseTexture);
  20676. BABYLON.Texture = Texture;
  20677. })(BABYLON || (BABYLON = {}));
  20678. var BABYLON;
  20679. (function (BABYLON) {
  20680. var CubeTexture = (function (_super) {
  20681. __extends(CubeTexture, _super);
  20682. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20683. _super.call(this, scene);
  20684. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20685. this.name = rootUrl;
  20686. this.url = rootUrl;
  20687. this._noMipmap = noMipmap;
  20688. this.hasAlpha = false;
  20689. if (!rootUrl && !files) {
  20690. return;
  20691. }
  20692. this._texture = this._getFromCache(rootUrl, noMipmap);
  20693. if (!files) {
  20694. if (!extensions) {
  20695. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20696. }
  20697. files = [];
  20698. for (var index = 0; index < extensions.length; index++) {
  20699. files.push(rootUrl + extensions[index]);
  20700. }
  20701. this._extensions = extensions;
  20702. }
  20703. this._files = files;
  20704. if (!this._texture) {
  20705. if (!scene.useDelayedTextureLoading) {
  20706. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20707. }
  20708. else {
  20709. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20710. }
  20711. }
  20712. this.isCube = true;
  20713. this._textureMatrix = BABYLON.Matrix.Identity();
  20714. }
  20715. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20716. return new CubeTexture("", scene, null, noMipmap, files);
  20717. };
  20718. // Methods
  20719. CubeTexture.prototype.delayLoad = function () {
  20720. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20721. return;
  20722. }
  20723. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20724. this._texture = this._getFromCache(this.url, this._noMipmap);
  20725. if (!this._texture) {
  20726. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20727. }
  20728. };
  20729. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20730. return this._textureMatrix;
  20731. };
  20732. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20733. var texture = BABYLON.SerializationHelper.Parse(function () {
  20734. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20735. }, parsedTexture, scene);
  20736. // Animations
  20737. if (parsedTexture.animations) {
  20738. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20739. var parsedAnimation = parsedTexture.animations[animationIndex];
  20740. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20741. }
  20742. }
  20743. return texture;
  20744. };
  20745. CubeTexture.prototype.clone = function () {
  20746. var _this = this;
  20747. return BABYLON.SerializationHelper.Clone(function () {
  20748. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20749. }, this);
  20750. };
  20751. return CubeTexture;
  20752. })(BABYLON.BaseTexture);
  20753. BABYLON.CubeTexture = CubeTexture;
  20754. })(BABYLON || (BABYLON = {}));
  20755. var BABYLON;
  20756. (function (BABYLON) {
  20757. var RenderTargetTexture = (function (_super) {
  20758. __extends(RenderTargetTexture, _super);
  20759. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20760. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20761. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20762. if (isCube === void 0) { isCube = false; }
  20763. _super.call(this, null, scene, !generateMipMaps);
  20764. this.isCube = isCube;
  20765. this.renderList = new Array();
  20766. this.renderParticles = true;
  20767. this.renderSprites = false;
  20768. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20769. this._currentRefreshId = -1;
  20770. this._refreshRate = 1;
  20771. this.name = name;
  20772. this.isRenderTarget = true;
  20773. this._size = size;
  20774. this._generateMipMaps = generateMipMaps;
  20775. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  20776. if (isCube) {
  20777. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20778. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  20779. this._textureMatrix = BABYLON.Matrix.Identity();
  20780. }
  20781. else {
  20782. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  20783. }
  20784. // Rendering groups
  20785. this._renderingManager = new BABYLON.RenderingManager(scene);
  20786. }
  20787. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  20788. get: function () {
  20789. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  20790. },
  20791. enumerable: true,
  20792. configurable: true
  20793. });
  20794. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  20795. get: function () {
  20796. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  20797. },
  20798. enumerable: true,
  20799. configurable: true
  20800. });
  20801. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  20802. get: function () {
  20803. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  20804. },
  20805. enumerable: true,
  20806. configurable: true
  20807. });
  20808. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  20809. this._currentRefreshId = -1;
  20810. };
  20811. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  20812. get: function () {
  20813. return this._refreshRate;
  20814. },
  20815. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20816. set: function (value) {
  20817. this._refreshRate = value;
  20818. this.resetRefreshCounter();
  20819. },
  20820. enumerable: true,
  20821. configurable: true
  20822. });
  20823. RenderTargetTexture.prototype._shouldRender = function () {
  20824. if (this._currentRefreshId === -1) {
  20825. this._currentRefreshId = 1;
  20826. return true;
  20827. }
  20828. if (this.refreshRate === this._currentRefreshId) {
  20829. this._currentRefreshId = 1;
  20830. return true;
  20831. }
  20832. this._currentRefreshId++;
  20833. return false;
  20834. };
  20835. RenderTargetTexture.prototype.isReady = function () {
  20836. if (!this.getScene().renderTargetsEnabled) {
  20837. return false;
  20838. }
  20839. return _super.prototype.isReady.call(this);
  20840. };
  20841. RenderTargetTexture.prototype.getRenderSize = function () {
  20842. return this._size;
  20843. };
  20844. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  20845. get: function () {
  20846. return true;
  20847. },
  20848. enumerable: true,
  20849. configurable: true
  20850. });
  20851. RenderTargetTexture.prototype.scale = function (ratio) {
  20852. var newSize = this._size * ratio;
  20853. this.resize(newSize, this._generateMipMaps);
  20854. };
  20855. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  20856. if (this.isCube) {
  20857. return this._textureMatrix;
  20858. }
  20859. return _super.prototype.getReflectionTextureMatrix.call(this);
  20860. };
  20861. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  20862. this.releaseInternalTexture();
  20863. if (this.isCube) {
  20864. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  20865. }
  20866. else {
  20867. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20868. }
  20869. };
  20870. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  20871. var scene = this.getScene();
  20872. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20873. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  20874. }
  20875. if (this._waitingRenderList) {
  20876. this.renderList = [];
  20877. for (var index = 0; index < this._waitingRenderList.length; index++) {
  20878. var id = this._waitingRenderList[index];
  20879. this.renderList.push(scene.getMeshByID(id));
  20880. }
  20881. delete this._waitingRenderList;
  20882. }
  20883. if (this.renderList && this.renderList.length === 0) {
  20884. return;
  20885. }
  20886. // Prepare renderingManager
  20887. this._renderingManager.reset();
  20888. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  20889. var sceneRenderId = scene.getRenderId();
  20890. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  20891. var mesh = currentRenderList[meshIndex];
  20892. if (mesh) {
  20893. if (!mesh.isReady()) {
  20894. // Reset _currentRefreshId
  20895. this.resetRefreshCounter();
  20896. continue;
  20897. }
  20898. mesh._preActivateForIntermediateRendering(sceneRenderId);
  20899. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  20900. mesh._activate(sceneRenderId);
  20901. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  20902. var subMesh = mesh.subMeshes[subIndex];
  20903. scene._activeIndices += subMesh.indexCount;
  20904. this._renderingManager.dispatch(subMesh);
  20905. }
  20906. }
  20907. }
  20908. }
  20909. if (this.isCube) {
  20910. for (var face = 0; face < 6; face++) {
  20911. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  20912. scene.incrementRenderId();
  20913. scene.resetCachedMaterial();
  20914. }
  20915. }
  20916. else {
  20917. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  20918. }
  20919. if (this.onAfterUnbind) {
  20920. this.onAfterUnbind();
  20921. }
  20922. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20923. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  20924. }
  20925. scene.resetCachedMaterial();
  20926. };
  20927. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  20928. var scene = this.getScene();
  20929. var engine = scene.getEngine();
  20930. // Bind
  20931. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  20932. if (this.isCube) {
  20933. engine.bindFramebuffer(this._texture, faceIndex);
  20934. }
  20935. else {
  20936. engine.bindFramebuffer(this._texture);
  20937. }
  20938. }
  20939. if (this.onBeforeRender) {
  20940. this.onBeforeRender(faceIndex);
  20941. }
  20942. // Clear
  20943. if (this.onClear) {
  20944. this.onClear(engine);
  20945. }
  20946. else {
  20947. engine.clear(scene.clearColor, true, true);
  20948. }
  20949. if (!this._doNotChangeAspectRatio) {
  20950. scene.updateTransformMatrix(true);
  20951. }
  20952. // Render
  20953. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  20954. if (useCameraPostProcess) {
  20955. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  20956. }
  20957. if (!this._doNotChangeAspectRatio) {
  20958. scene.updateTransformMatrix(true);
  20959. }
  20960. if (this.onAfterRender) {
  20961. this.onAfterRender(faceIndex);
  20962. }
  20963. // Dump ?
  20964. if (dumpForDebug) {
  20965. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  20966. }
  20967. // Unbind
  20968. if (!this.isCube || faceIndex === 5) {
  20969. if (this.isCube) {
  20970. if (faceIndex === 5) {
  20971. engine.generateMipMapsForCubemap(this._texture);
  20972. }
  20973. }
  20974. engine.unBindFramebuffer(this._texture, this.isCube);
  20975. }
  20976. };
  20977. RenderTargetTexture.prototype.clone = function () {
  20978. var textureSize = this.getSize();
  20979. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20980. // Base texture
  20981. newTexture.hasAlpha = this.hasAlpha;
  20982. newTexture.level = this.level;
  20983. // RenderTarget Texture
  20984. newTexture.coordinatesMode = this.coordinatesMode;
  20985. newTexture.renderList = this.renderList.slice(0);
  20986. return newTexture;
  20987. };
  20988. RenderTargetTexture.prototype.serialize = function () {
  20989. if (!this.name) {
  20990. return null;
  20991. }
  20992. var serializationObject = _super.prototype.serialize.call(this);
  20993. serializationObject.renderTargetSize = this.getRenderSize();
  20994. serializationObject.renderList = [];
  20995. for (var index = 0; index < this.renderList.length; index++) {
  20996. serializationObject.renderList.push(this.renderList[index].id);
  20997. }
  20998. return serializationObject;
  20999. };
  21000. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  21001. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  21002. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  21003. return RenderTargetTexture;
  21004. })(BABYLON.Texture);
  21005. BABYLON.RenderTargetTexture = RenderTargetTexture;
  21006. })(BABYLON || (BABYLON = {}));
  21007. var BABYLON;
  21008. (function (BABYLON) {
  21009. var ProceduralTexture = (function (_super) {
  21010. __extends(ProceduralTexture, _super);
  21011. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  21012. if (generateMipMaps === void 0) { generateMipMaps = true; }
  21013. if (isCube === void 0) { isCube = false; }
  21014. _super.call(this, null, scene, !generateMipMaps);
  21015. this.isCube = isCube;
  21016. this.isEnabled = true;
  21017. this._currentRefreshId = -1;
  21018. this._refreshRate = 1;
  21019. this._vertexDeclaration = [2];
  21020. this._vertexStrideSize = 2 * 4;
  21021. this._uniforms = new Array();
  21022. this._samplers = new Array();
  21023. this._textures = new Array();
  21024. this._floats = new Array();
  21025. this._floatsArrays = {};
  21026. this._colors3 = new Array();
  21027. this._colors4 = new Array();
  21028. this._vectors2 = new Array();
  21029. this._vectors3 = new Array();
  21030. this._matrices = new Array();
  21031. this._fallbackTextureUsed = false;
  21032. scene._proceduralTextures.push(this);
  21033. this.name = name;
  21034. this.isRenderTarget = true;
  21035. this._size = size;
  21036. this._generateMipMaps = generateMipMaps;
  21037. this.setFragment(fragment);
  21038. this._fallbackTexture = fallbackTexture;
  21039. if (isCube) {
  21040. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21041. this.setFloat("face", 0);
  21042. }
  21043. else {
  21044. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  21045. }
  21046. // VBO
  21047. var vertices = [];
  21048. vertices.push(1, 1);
  21049. vertices.push(-1, 1);
  21050. vertices.push(-1, -1);
  21051. vertices.push(1, -1);
  21052. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21053. // Indices
  21054. var indices = [];
  21055. indices.push(0);
  21056. indices.push(1);
  21057. indices.push(2);
  21058. indices.push(0);
  21059. indices.push(2);
  21060. indices.push(3);
  21061. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21062. }
  21063. ProceduralTexture.prototype.reset = function () {
  21064. if (this._effect === undefined) {
  21065. return;
  21066. }
  21067. var engine = this.getScene().getEngine();
  21068. engine._releaseEffect(this._effect);
  21069. };
  21070. ProceduralTexture.prototype.isReady = function () {
  21071. var _this = this;
  21072. var engine = this.getScene().getEngine();
  21073. var shaders;
  21074. if (!this._fragment) {
  21075. return false;
  21076. }
  21077. if (this._fallbackTextureUsed) {
  21078. return true;
  21079. }
  21080. if (this._fragment.fragmentElement !== undefined) {
  21081. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  21082. }
  21083. else {
  21084. shaders = { vertex: "procedural", fragment: this._fragment };
  21085. }
  21086. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  21087. _this.releaseInternalTexture();
  21088. if (_this._fallbackTexture) {
  21089. _this._texture = _this._fallbackTexture._texture;
  21090. _this._texture.references++;
  21091. }
  21092. _this._fallbackTextureUsed = true;
  21093. });
  21094. return this._effect.isReady();
  21095. };
  21096. ProceduralTexture.prototype.resetRefreshCounter = function () {
  21097. this._currentRefreshId = -1;
  21098. };
  21099. ProceduralTexture.prototype.setFragment = function (fragment) {
  21100. this._fragment = fragment;
  21101. };
  21102. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  21103. get: function () {
  21104. return this._refreshRate;
  21105. },
  21106. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21107. set: function (value) {
  21108. this._refreshRate = value;
  21109. this.resetRefreshCounter();
  21110. },
  21111. enumerable: true,
  21112. configurable: true
  21113. });
  21114. ProceduralTexture.prototype._shouldRender = function () {
  21115. if (!this.isEnabled || !this.isReady() || !this._texture) {
  21116. return false;
  21117. }
  21118. if (this._fallbackTextureUsed) {
  21119. return false;
  21120. }
  21121. if (this._currentRefreshId === -1) {
  21122. this._currentRefreshId = 1;
  21123. return true;
  21124. }
  21125. if (this.refreshRate === this._currentRefreshId) {
  21126. this._currentRefreshId = 1;
  21127. return true;
  21128. }
  21129. this._currentRefreshId++;
  21130. return false;
  21131. };
  21132. ProceduralTexture.prototype.getRenderSize = function () {
  21133. return this._size;
  21134. };
  21135. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  21136. if (this._fallbackTextureUsed) {
  21137. return;
  21138. }
  21139. this.releaseInternalTexture();
  21140. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21141. };
  21142. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  21143. if (this._uniforms.indexOf(uniformName) === -1) {
  21144. this._uniforms.push(uniformName);
  21145. }
  21146. };
  21147. ProceduralTexture.prototype.setTexture = function (name, texture) {
  21148. if (this._samplers.indexOf(name) === -1) {
  21149. this._samplers.push(name);
  21150. }
  21151. this._textures[name] = texture;
  21152. return this;
  21153. };
  21154. ProceduralTexture.prototype.setFloat = function (name, value) {
  21155. this._checkUniform(name);
  21156. this._floats[name] = value;
  21157. return this;
  21158. };
  21159. ProceduralTexture.prototype.setFloats = function (name, value) {
  21160. this._checkUniform(name);
  21161. this._floatsArrays[name] = value;
  21162. return this;
  21163. };
  21164. ProceduralTexture.prototype.setColor3 = function (name, value) {
  21165. this._checkUniform(name);
  21166. this._colors3[name] = value;
  21167. return this;
  21168. };
  21169. ProceduralTexture.prototype.setColor4 = function (name, value) {
  21170. this._checkUniform(name);
  21171. this._colors4[name] = value;
  21172. return this;
  21173. };
  21174. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21175. this._checkUniform(name);
  21176. this._vectors2[name] = value;
  21177. return this;
  21178. };
  21179. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21180. this._checkUniform(name);
  21181. this._vectors3[name] = value;
  21182. return this;
  21183. };
  21184. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21185. this._checkUniform(name);
  21186. this._matrices[name] = value;
  21187. return this;
  21188. };
  21189. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21190. var scene = this.getScene();
  21191. var engine = scene.getEngine();
  21192. // Render
  21193. engine.enableEffect(this._effect);
  21194. engine.setState(false);
  21195. // Texture
  21196. for (var name in this._textures) {
  21197. this._effect.setTexture(name, this._textures[name]);
  21198. }
  21199. // Float
  21200. for (name in this._floats) {
  21201. this._effect.setFloat(name, this._floats[name]);
  21202. }
  21203. // Floats
  21204. for (name in this._floatsArrays) {
  21205. this._effect.setArray(name, this._floatsArrays[name]);
  21206. }
  21207. // Color3
  21208. for (name in this._colors3) {
  21209. this._effect.setColor3(name, this._colors3[name]);
  21210. }
  21211. // Color4
  21212. for (name in this._colors4) {
  21213. var color = this._colors4[name];
  21214. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21215. }
  21216. // Vector2
  21217. for (name in this._vectors2) {
  21218. this._effect.setVector2(name, this._vectors2[name]);
  21219. }
  21220. // Vector3
  21221. for (name in this._vectors3) {
  21222. this._effect.setVector3(name, this._vectors3[name]);
  21223. }
  21224. // Matrix
  21225. for (name in this._matrices) {
  21226. this._effect.setMatrix(name, this._matrices[name]);
  21227. }
  21228. // VBOs
  21229. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21230. if (this.isCube) {
  21231. for (var face = 0; face < 6; face++) {
  21232. engine.bindFramebuffer(this._texture, face);
  21233. this._effect.setFloat("face", face);
  21234. // Clear
  21235. engine.clear(scene.clearColor, true, true);
  21236. // Draw order
  21237. engine.draw(true, 0, 6);
  21238. // Mipmaps
  21239. if (face === 5) {
  21240. engine.generateMipMapsForCubemap(this._texture);
  21241. }
  21242. }
  21243. }
  21244. else {
  21245. engine.bindFramebuffer(this._texture);
  21246. // Clear
  21247. engine.clear(scene.clearColor, true, true);
  21248. // Draw order
  21249. engine.draw(true, 0, 6);
  21250. }
  21251. // Unbind
  21252. engine.unBindFramebuffer(this._texture, this.isCube);
  21253. if (this.onGenerated) {
  21254. this.onGenerated();
  21255. }
  21256. };
  21257. ProceduralTexture.prototype.clone = function () {
  21258. var textureSize = this.getSize();
  21259. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21260. // Base texture
  21261. newTexture.hasAlpha = this.hasAlpha;
  21262. newTexture.level = this.level;
  21263. // RenderTarget Texture
  21264. newTexture.coordinatesMode = this.coordinatesMode;
  21265. return newTexture;
  21266. };
  21267. ProceduralTexture.prototype.dispose = function () {
  21268. var index = this.getScene()._proceduralTextures.indexOf(this);
  21269. if (index >= 0) {
  21270. this.getScene()._proceduralTextures.splice(index, 1);
  21271. }
  21272. _super.prototype.dispose.call(this);
  21273. };
  21274. return ProceduralTexture;
  21275. })(BABYLON.Texture);
  21276. BABYLON.ProceduralTexture = ProceduralTexture;
  21277. })(BABYLON || (BABYLON = {}));
  21278. var BABYLON;
  21279. (function (BABYLON) {
  21280. var MirrorTexture = (function (_super) {
  21281. __extends(MirrorTexture, _super);
  21282. function MirrorTexture(name, size, scene, generateMipMaps) {
  21283. var _this = this;
  21284. _super.call(this, name, size, scene, generateMipMaps, true);
  21285. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21286. this._transformMatrix = BABYLON.Matrix.Zero();
  21287. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21288. this.onBeforeRender = function () {
  21289. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21290. _this._savedViewMatrix = scene.getViewMatrix();
  21291. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21292. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21293. scene.clipPlane = _this.mirrorPlane;
  21294. scene.getEngine().cullBackFaces = false;
  21295. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21296. };
  21297. this.onAfterRender = function () {
  21298. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21299. scene.getEngine().cullBackFaces = true;
  21300. scene._mirroredCameraPosition = null;
  21301. delete scene.clipPlane;
  21302. };
  21303. }
  21304. MirrorTexture.prototype.clone = function () {
  21305. var textureSize = this.getSize();
  21306. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21307. // Base texture
  21308. newTexture.hasAlpha = this.hasAlpha;
  21309. newTexture.level = this.level;
  21310. // Mirror Texture
  21311. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21312. newTexture.renderList = this.renderList.slice(0);
  21313. return newTexture;
  21314. };
  21315. MirrorTexture.prototype.serialize = function () {
  21316. if (!this.name) {
  21317. return null;
  21318. }
  21319. var serializationObject = _super.prototype.serialize.call(this);
  21320. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21321. return serializationObject;
  21322. };
  21323. return MirrorTexture;
  21324. })(BABYLON.RenderTargetTexture);
  21325. BABYLON.MirrorTexture = MirrorTexture;
  21326. })(BABYLON || (BABYLON = {}));
  21327. var BABYLON;
  21328. (function (BABYLON) {
  21329. /**
  21330. * Creates a refraction texture used by refraction channel of the standard material.
  21331. * @param name the texture name
  21332. * @param size size of the underlying texture
  21333. * @param scene root scene
  21334. */
  21335. var RefractionTexture = (function (_super) {
  21336. __extends(RefractionTexture, _super);
  21337. function RefractionTexture(name, size, scene, generateMipMaps) {
  21338. var _this = this;
  21339. _super.call(this, name, size, scene, generateMipMaps, true);
  21340. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21341. this.depth = 2.0;
  21342. this.onBeforeRender = function () {
  21343. scene.clipPlane = _this.refractionPlane;
  21344. };
  21345. this.onAfterRender = function () {
  21346. delete scene.clipPlane;
  21347. };
  21348. }
  21349. RefractionTexture.prototype.clone = function () {
  21350. var textureSize = this.getSize();
  21351. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21352. // Base texture
  21353. newTexture.hasAlpha = this.hasAlpha;
  21354. newTexture.level = this.level;
  21355. // Refraction Texture
  21356. newTexture.refractionPlane = this.refractionPlane.clone();
  21357. newTexture.renderList = this.renderList.slice(0);
  21358. newTexture.depth = this.depth;
  21359. return newTexture;
  21360. };
  21361. RefractionTexture.prototype.serialize = function () {
  21362. if (!this.name) {
  21363. return null;
  21364. }
  21365. var serializationObject = _super.prototype.serialize.call(this);
  21366. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21367. serializationObject.depth = this.depth;
  21368. return serializationObject;
  21369. };
  21370. return RefractionTexture;
  21371. })(BABYLON.RenderTargetTexture);
  21372. BABYLON.RefractionTexture = RefractionTexture;
  21373. })(BABYLON || (BABYLON = {}));
  21374. var BABYLON;
  21375. (function (BABYLON) {
  21376. var DynamicTexture = (function (_super) {
  21377. __extends(DynamicTexture, _super);
  21378. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21379. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21380. _super.call(this, null, scene, !generateMipMaps);
  21381. this.name = name;
  21382. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21383. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21384. this._generateMipMaps = generateMipMaps;
  21385. if (options.getContext) {
  21386. this._canvas = options;
  21387. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21388. }
  21389. else {
  21390. this._canvas = document.createElement("canvas");
  21391. if (options.width) {
  21392. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21393. }
  21394. else {
  21395. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21396. }
  21397. }
  21398. var textureSize = this.getSize();
  21399. this._canvas.width = textureSize.width;
  21400. this._canvas.height = textureSize.height;
  21401. this._context = this._canvas.getContext("2d");
  21402. }
  21403. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21404. get: function () {
  21405. return true;
  21406. },
  21407. enumerable: true,
  21408. configurable: true
  21409. });
  21410. DynamicTexture.prototype.scale = function (ratio) {
  21411. var textureSize = this.getSize();
  21412. textureSize.width *= ratio;
  21413. textureSize.height *= ratio;
  21414. this._canvas.width = textureSize.width;
  21415. this._canvas.height = textureSize.height;
  21416. this.releaseInternalTexture();
  21417. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21418. };
  21419. DynamicTexture.prototype.getContext = function () {
  21420. return this._context;
  21421. };
  21422. DynamicTexture.prototype.clear = function () {
  21423. var size = this.getSize();
  21424. this._context.fillRect(0, 0, size.width, size.height);
  21425. };
  21426. DynamicTexture.prototype.update = function (invertY) {
  21427. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21428. };
  21429. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21430. if (update === void 0) { update = true; }
  21431. var size = this.getSize();
  21432. if (clearColor) {
  21433. this._context.fillStyle = clearColor;
  21434. this._context.fillRect(0, 0, size.width, size.height);
  21435. }
  21436. this._context.font = font;
  21437. if (x === null) {
  21438. var textSize = this._context.measureText(text);
  21439. x = (size.width - textSize.width) / 2;
  21440. }
  21441. this._context.fillStyle = color;
  21442. this._context.fillText(text, x, y);
  21443. if (update) {
  21444. this.update(invertY);
  21445. }
  21446. };
  21447. DynamicTexture.prototype.clone = function () {
  21448. var textureSize = this.getSize();
  21449. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21450. // Base texture
  21451. newTexture.hasAlpha = this.hasAlpha;
  21452. newTexture.level = this.level;
  21453. // Dynamic Texture
  21454. newTexture.wrapU = this.wrapU;
  21455. newTexture.wrapV = this.wrapV;
  21456. return newTexture;
  21457. };
  21458. return DynamicTexture;
  21459. })(BABYLON.Texture);
  21460. BABYLON.DynamicTexture = DynamicTexture;
  21461. })(BABYLON || (BABYLON = {}));
  21462. var BABYLON;
  21463. (function (BABYLON) {
  21464. var VideoTexture = (function (_super) {
  21465. __extends(VideoTexture, _super);
  21466. /**
  21467. * Creates a video texture.
  21468. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21469. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21470. * @param {BABYLON.Scene} scene is obviously the current scene.
  21471. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21472. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21473. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21474. */
  21475. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21476. var _this = this;
  21477. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21478. if (invertY === void 0) { invertY = false; }
  21479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21480. _super.call(this, null, scene, !generateMipMaps, invertY);
  21481. this._autoLaunch = true;
  21482. var urls;
  21483. this.name = name;
  21484. if (urlsOrVideo instanceof HTMLVideoElement) {
  21485. this.video = urlsOrVideo;
  21486. }
  21487. else {
  21488. urls = urlsOrVideo;
  21489. this.video = document.createElement("video");
  21490. this.video.autoplay = false;
  21491. this.video.loop = true;
  21492. }
  21493. this._generateMipMaps = generateMipMaps;
  21494. this._samplingMode = samplingMode;
  21495. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21496. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21497. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21498. }
  21499. else {
  21500. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21501. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21502. this._generateMipMaps = false;
  21503. }
  21504. if (urls) {
  21505. this.video.addEventListener("canplaythrough", function () {
  21506. _this._createTexture();
  21507. });
  21508. urls.forEach(function (url) {
  21509. var source = document.createElement("source");
  21510. source.src = url;
  21511. _this.video.appendChild(source);
  21512. });
  21513. }
  21514. else {
  21515. this._createTexture();
  21516. }
  21517. this._lastUpdate = BABYLON.Tools.Now;
  21518. }
  21519. VideoTexture.prototype._createTexture = function () {
  21520. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21521. this._texture.isReady = true;
  21522. };
  21523. VideoTexture.prototype.update = function () {
  21524. if (this._autoLaunch) {
  21525. this._autoLaunch = false;
  21526. this.video.play();
  21527. }
  21528. var now = BABYLON.Tools.Now;
  21529. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21530. return false;
  21531. }
  21532. this._lastUpdate = now;
  21533. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21534. return true;
  21535. };
  21536. return VideoTexture;
  21537. })(BABYLON.Texture);
  21538. BABYLON.VideoTexture = VideoTexture;
  21539. })(BABYLON || (BABYLON = {}));
  21540. var BABYLON;
  21541. (function (BABYLON) {
  21542. var CustomProceduralTexture = (function (_super) {
  21543. __extends(CustomProceduralTexture, _super);
  21544. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21545. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21546. this._animate = true;
  21547. this._time = 0;
  21548. this._texturePath = texturePath;
  21549. //Try to load json
  21550. this.loadJson(texturePath);
  21551. this.refreshRate = 1;
  21552. }
  21553. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21554. var _this = this;
  21555. var that = this;
  21556. function noConfigFile() {
  21557. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21558. try {
  21559. that.setFragment(that._texturePath);
  21560. }
  21561. catch (ex) {
  21562. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21563. }
  21564. }
  21565. var configFileUrl = jsonUrl + "/config.json";
  21566. var xhr = new XMLHttpRequest();
  21567. xhr.open("GET", configFileUrl, true);
  21568. xhr.addEventListener("load", function () {
  21569. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21570. try {
  21571. _this._config = JSON.parse(xhr.response);
  21572. _this.updateShaderUniforms();
  21573. _this.updateTextures();
  21574. _this.setFragment(_this._texturePath + "/custom");
  21575. _this._animate = _this._config.animate;
  21576. _this.refreshRate = _this._config.refreshrate;
  21577. }
  21578. catch (ex) {
  21579. noConfigFile();
  21580. }
  21581. }
  21582. else {
  21583. noConfigFile();
  21584. }
  21585. }, false);
  21586. xhr.addEventListener("error", function () {
  21587. noConfigFile();
  21588. }, false);
  21589. try {
  21590. xhr.send();
  21591. }
  21592. catch (ex) {
  21593. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  21594. }
  21595. };
  21596. CustomProceduralTexture.prototype.isReady = function () {
  21597. if (!_super.prototype.isReady.call(this)) {
  21598. return false;
  21599. }
  21600. for (var name in this._textures) {
  21601. var texture = this._textures[name];
  21602. if (!texture.isReady()) {
  21603. return false;
  21604. }
  21605. }
  21606. return true;
  21607. };
  21608. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21609. if (this._animate) {
  21610. this._time += this.getScene().getAnimationRatio() * 0.03;
  21611. this.updateShaderUniforms();
  21612. }
  21613. _super.prototype.render.call(this, useCameraPostProcess);
  21614. };
  21615. CustomProceduralTexture.prototype.updateTextures = function () {
  21616. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  21617. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  21618. }
  21619. };
  21620. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  21621. if (this._config) {
  21622. for (var j = 0; j < this._config.uniforms.length; j++) {
  21623. var uniform = this._config.uniforms[j];
  21624. switch (uniform.type) {
  21625. case "float":
  21626. this.setFloat(uniform.name, uniform.value);
  21627. break;
  21628. case "color3":
  21629. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  21630. break;
  21631. case "color4":
  21632. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  21633. break;
  21634. case "vector2":
  21635. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  21636. break;
  21637. case "vector3":
  21638. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  21639. break;
  21640. }
  21641. }
  21642. }
  21643. this.setFloat("time", this._time);
  21644. };
  21645. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  21646. get: function () {
  21647. return this._animate;
  21648. },
  21649. set: function (value) {
  21650. this._animate = value;
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. return CustomProceduralTexture;
  21656. })(BABYLON.ProceduralTexture);
  21657. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21658. })(BABYLON || (BABYLON = {}));
  21659. var BABYLON;
  21660. (function (BABYLON) {
  21661. var EffectFallbacks = (function () {
  21662. function EffectFallbacks() {
  21663. this._defines = {};
  21664. this._currentRank = 32;
  21665. this._maxRank = -1;
  21666. }
  21667. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21668. if (!this._defines[rank]) {
  21669. if (rank < this._currentRank) {
  21670. this._currentRank = rank;
  21671. }
  21672. if (rank > this._maxRank) {
  21673. this._maxRank = rank;
  21674. }
  21675. this._defines[rank] = new Array();
  21676. }
  21677. this._defines[rank].push(define);
  21678. };
  21679. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21680. this._meshRank = rank;
  21681. this._mesh = mesh;
  21682. if (rank > this._maxRank) {
  21683. this._maxRank = rank;
  21684. }
  21685. };
  21686. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21687. get: function () {
  21688. return this._currentRank <= this._maxRank;
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21694. var currentFallbacks = this._defines[this._currentRank];
  21695. for (var index = 0; index < currentFallbacks.length; index++) {
  21696. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21697. }
  21698. if (this._mesh && this._currentRank === this._meshRank) {
  21699. this._mesh.computeBonesUsingShaders = false;
  21700. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21701. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21702. }
  21703. this._currentRank++;
  21704. return currentDefines;
  21705. };
  21706. return EffectFallbacks;
  21707. })();
  21708. BABYLON.EffectFallbacks = EffectFallbacks;
  21709. var Effect = (function () {
  21710. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  21711. var _this = this;
  21712. this._isReady = false;
  21713. this._compilationError = "";
  21714. this._valueCache = [];
  21715. this._engine = engine;
  21716. this.name = baseName;
  21717. this.defines = defines;
  21718. this._uniformsNames = uniformsNames.concat(samplers);
  21719. this._samplers = samplers;
  21720. this._attributesNames = attributesNames;
  21721. this.onError = onError;
  21722. this.onCompiled = onCompiled;
  21723. var vertexSource;
  21724. var fragmentSource;
  21725. if (baseName.vertexElement) {
  21726. vertexSource = document.getElementById(baseName.vertexElement);
  21727. if (!vertexSource) {
  21728. vertexSource = baseName.vertexElement;
  21729. }
  21730. }
  21731. else {
  21732. vertexSource = baseName.vertex || baseName;
  21733. }
  21734. if (baseName.fragmentElement) {
  21735. fragmentSource = document.getElementById(baseName.fragmentElement);
  21736. if (!fragmentSource) {
  21737. fragmentSource = baseName.fragmentElement;
  21738. }
  21739. }
  21740. else {
  21741. fragmentSource = baseName.fragment || baseName;
  21742. }
  21743. this._loadVertexShader(vertexSource, function (vertexCode) {
  21744. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21745. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21746. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21747. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  21748. });
  21749. });
  21750. });
  21751. });
  21752. }
  21753. // Properties
  21754. Effect.prototype.isReady = function () {
  21755. return this._isReady;
  21756. };
  21757. Effect.prototype.getProgram = function () {
  21758. return this._program;
  21759. };
  21760. Effect.prototype.getAttributesNames = function () {
  21761. return this._attributesNames;
  21762. };
  21763. Effect.prototype.getAttributeLocation = function (index) {
  21764. return this._attributes[index];
  21765. };
  21766. Effect.prototype.getAttributeLocationByName = function (name) {
  21767. var index = this._attributesNames.indexOf(name);
  21768. return this._attributes[index];
  21769. };
  21770. Effect.prototype.getAttributesCount = function () {
  21771. return this._attributes.length;
  21772. };
  21773. Effect.prototype.getUniformIndex = function (uniformName) {
  21774. return this._uniformsNames.indexOf(uniformName);
  21775. };
  21776. Effect.prototype.getUniform = function (uniformName) {
  21777. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21778. };
  21779. Effect.prototype.getSamplers = function () {
  21780. return this._samplers;
  21781. };
  21782. Effect.prototype.getCompilationError = function () {
  21783. return this._compilationError;
  21784. };
  21785. // Methods
  21786. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21787. // DOM element ?
  21788. if (vertex instanceof HTMLElement) {
  21789. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21790. callback(vertexCode);
  21791. return;
  21792. }
  21793. // Is in local store ?
  21794. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21795. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21796. return;
  21797. }
  21798. var vertexShaderUrl;
  21799. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21800. vertexShaderUrl = vertex;
  21801. }
  21802. else {
  21803. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21804. }
  21805. // Vertex shader
  21806. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21807. };
  21808. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21809. // DOM element ?
  21810. if (fragment instanceof HTMLElement) {
  21811. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21812. callback(fragmentCode);
  21813. return;
  21814. }
  21815. // Is in local store ?
  21816. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21817. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21818. return;
  21819. }
  21820. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21821. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21822. return;
  21823. }
  21824. var fragmentShaderUrl;
  21825. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21826. fragmentShaderUrl = fragment;
  21827. }
  21828. else {
  21829. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21830. }
  21831. // Fragment shader
  21832. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21833. };
  21834. Effect.prototype._dumpShadersName = function () {
  21835. if (this.name.vertexElement) {
  21836. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21837. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21838. }
  21839. else if (this.name.vertex) {
  21840. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21841. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21842. }
  21843. else {
  21844. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21845. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21846. }
  21847. };
  21848. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21849. var _this = this;
  21850. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21851. var match = regex.exec(sourceCode);
  21852. var returnValue = new String(sourceCode);
  21853. while (match != null) {
  21854. var includeFile = match[1];
  21855. if (Effect.IncludesShadersStore[includeFile]) {
  21856. // Substitution
  21857. var includeContent = Effect.IncludesShadersStore[includeFile];
  21858. if (match[2]) {
  21859. var splits = match[3].split(",");
  21860. for (var index = 0; index < splits.length; index += 2) {
  21861. var source = new RegExp(splits[index], "g");
  21862. var dest = splits[index + 1];
  21863. includeContent = includeContent.replace(source, dest);
  21864. }
  21865. }
  21866. if (match[4]) {
  21867. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  21868. }
  21869. // Replace
  21870. returnValue = returnValue.replace(match[0], includeContent);
  21871. }
  21872. else {
  21873. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21874. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21875. Effect.IncludesShadersStore[includeFile] = fileContent;
  21876. _this._processIncludes(returnValue, callback);
  21877. });
  21878. return;
  21879. }
  21880. match = regex.exec(sourceCode);
  21881. }
  21882. callback(returnValue);
  21883. };
  21884. Effect.prototype._processPrecision = function (source) {
  21885. if (source.indexOf("precision highp float") === -1) {
  21886. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21887. source = "precision mediump float;\n" + source;
  21888. }
  21889. else {
  21890. source = "precision highp float;\n" + source;
  21891. }
  21892. }
  21893. else {
  21894. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21895. source = source.replace("precision highp float", "precision mediump float");
  21896. }
  21897. }
  21898. return source;
  21899. };
  21900. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21901. try {
  21902. var engine = this._engine;
  21903. // Precision
  21904. vertexSourceCode = this._processPrecision(vertexSourceCode);
  21905. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  21906. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21907. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21908. this._attributes = engine.getAttributes(this._program, attributesNames);
  21909. for (var index = 0; index < this._samplers.length; index++) {
  21910. var sampler = this.getUniform(this._samplers[index]);
  21911. if (sampler == null) {
  21912. this._samplers.splice(index, 1);
  21913. index--;
  21914. }
  21915. }
  21916. engine.bindSamplers(this);
  21917. this._isReady = true;
  21918. if (this.onCompiled) {
  21919. this.onCompiled(this);
  21920. }
  21921. }
  21922. catch (e) {
  21923. // Is it a problem with precision?
  21924. if (e.message.indexOf("highp") !== -1) {
  21925. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  21926. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  21927. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21928. return;
  21929. }
  21930. // Let's go through fallbacks then
  21931. if (fallbacks && fallbacks.isMoreFallbacks) {
  21932. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  21933. this._dumpShadersName();
  21934. defines = fallbacks.reduce(defines);
  21935. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21936. }
  21937. else {
  21938. BABYLON.Tools.Error("Unable to compile effect: ");
  21939. this._dumpShadersName();
  21940. BABYLON.Tools.Error("Defines: " + defines);
  21941. BABYLON.Tools.Error("Error: " + e.message);
  21942. this._compilationError = e.message;
  21943. if (this.onError) {
  21944. this.onError(this, this._compilationError);
  21945. }
  21946. }
  21947. }
  21948. };
  21949. Object.defineProperty(Effect.prototype, "isSupported", {
  21950. get: function () {
  21951. return this._compilationError === "";
  21952. },
  21953. enumerable: true,
  21954. configurable: true
  21955. });
  21956. Effect.prototype._bindTexture = function (channel, texture) {
  21957. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21958. };
  21959. Effect.prototype.setTexture = function (channel, texture) {
  21960. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  21961. };
  21962. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21963. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21964. };
  21965. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21966. if (!this._valueCache[uniformName]) {
  21967. this._valueCache[uniformName] = new BABYLON.Matrix();
  21968. }
  21969. for (var index = 0; index < 16; index++) {
  21970. this._valueCache[uniformName].m[index] = matrix.m[index];
  21971. }
  21972. };
  21973. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21974. if (!this._valueCache[uniformName]) {
  21975. this._valueCache[uniformName] = [x, y];
  21976. return;
  21977. }
  21978. this._valueCache[uniformName][0] = x;
  21979. this._valueCache[uniformName][1] = y;
  21980. };
  21981. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21982. if (!this._valueCache[uniformName]) {
  21983. this._valueCache[uniformName] = [x, y, z];
  21984. return;
  21985. }
  21986. this._valueCache[uniformName][0] = x;
  21987. this._valueCache[uniformName][1] = y;
  21988. this._valueCache[uniformName][2] = z;
  21989. };
  21990. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21991. if (!this._valueCache[uniformName]) {
  21992. this._valueCache[uniformName] = [x, y, z, w];
  21993. return;
  21994. }
  21995. this._valueCache[uniformName][0] = x;
  21996. this._valueCache[uniformName][1] = y;
  21997. this._valueCache[uniformName][2] = z;
  21998. this._valueCache[uniformName][3] = w;
  21999. };
  22000. Effect.prototype.setArray = function (uniformName, array) {
  22001. this._engine.setArray(this.getUniform(uniformName), array);
  22002. return this;
  22003. };
  22004. Effect.prototype.setArray2 = function (uniformName, array) {
  22005. this._engine.setArray2(this.getUniform(uniformName), array);
  22006. return this;
  22007. };
  22008. Effect.prototype.setArray3 = function (uniformName, array) {
  22009. this._engine.setArray3(this.getUniform(uniformName), array);
  22010. return this;
  22011. };
  22012. Effect.prototype.setArray4 = function (uniformName, array) {
  22013. this._engine.setArray4(this.getUniform(uniformName), array);
  22014. return this;
  22015. };
  22016. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22017. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22018. return this;
  22019. };
  22020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22021. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  22022. // return this;
  22023. // this._cacheMatrix(uniformName, matrix);
  22024. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22025. return this;
  22026. };
  22027. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22028. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22029. return this;
  22030. };
  22031. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  22032. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  22033. return this;
  22034. };
  22035. Effect.prototype.setFloat = function (uniformName, value) {
  22036. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  22037. return this;
  22038. this._valueCache[uniformName] = value;
  22039. this._engine.setFloat(this.getUniform(uniformName), value);
  22040. return this;
  22041. };
  22042. Effect.prototype.setBool = function (uniformName, bool) {
  22043. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  22044. return this;
  22045. this._valueCache[uniformName] = bool;
  22046. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22047. return this;
  22048. };
  22049. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22050. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  22051. return this;
  22052. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  22053. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22054. return this;
  22055. };
  22056. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22057. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  22058. return this;
  22059. this._cacheFloat2(uniformName, x, y);
  22060. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22061. return this;
  22062. };
  22063. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22064. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  22065. return this;
  22066. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  22067. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22068. return this;
  22069. };
  22070. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22071. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  22072. return this;
  22073. this._cacheFloat3(uniformName, x, y, z);
  22074. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22075. return this;
  22076. };
  22077. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22078. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  22079. return this;
  22080. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  22081. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22082. return this;
  22083. };
  22084. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22085. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  22086. return this;
  22087. this._cacheFloat4(uniformName, x, y, z, w);
  22088. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22089. return this;
  22090. };
  22091. Effect.prototype.setColor3 = function (uniformName, color3) {
  22092. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  22093. return this;
  22094. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  22095. this._engine.setColor3(this.getUniform(uniformName), color3);
  22096. return this;
  22097. };
  22098. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22099. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
  22100. return this;
  22101. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  22102. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22103. return this;
  22104. };
  22105. // Statics
  22106. Effect.ShadersStore = {};
  22107. Effect.IncludesShadersStore = {};
  22108. return Effect;
  22109. })();
  22110. BABYLON.Effect = Effect;
  22111. })(BABYLON || (BABYLON = {}));
  22112. var BABYLON;
  22113. (function (BABYLON) {
  22114. var maxSimultaneousLights = 4;
  22115. var MaterialHelper = (function () {
  22116. function MaterialHelper() {
  22117. }
  22118. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  22119. var lightIndex = 0;
  22120. var needNormals = false;
  22121. for (var index = 0; index < scene.lights.length; index++) {
  22122. var light = scene.lights[index];
  22123. if (!light.isEnabled()) {
  22124. continue;
  22125. }
  22126. // Excluded check
  22127. if (light._excludedMeshesIds.length > 0) {
  22128. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  22129. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  22130. if (excludedMesh) {
  22131. light.excludedMeshes.push(excludedMesh);
  22132. }
  22133. }
  22134. light._excludedMeshesIds = [];
  22135. }
  22136. // Included check
  22137. if (light._includedOnlyMeshesIds.length > 0) {
  22138. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  22139. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  22140. if (includedOnlyMesh) {
  22141. light.includedOnlyMeshes.push(includedOnlyMesh);
  22142. }
  22143. }
  22144. light._includedOnlyMeshesIds = [];
  22145. }
  22146. if (!light.canAffectMesh(mesh)) {
  22147. continue;
  22148. }
  22149. needNormals = true;
  22150. defines["LIGHT" + lightIndex] = true;
  22151. var type;
  22152. if (light instanceof BABYLON.SpotLight) {
  22153. type = "SPOTLIGHT" + lightIndex;
  22154. }
  22155. else if (light instanceof BABYLON.HemisphericLight) {
  22156. type = "HEMILIGHT" + lightIndex;
  22157. }
  22158. else if (light instanceof BABYLON.PointLight) {
  22159. type = "POINTLIGHT" + lightIndex;
  22160. }
  22161. else {
  22162. type = "DIRLIGHT" + lightIndex;
  22163. }
  22164. defines[type] = true;
  22165. // Specular
  22166. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  22167. defines["SPECULARTERM"] = true;
  22168. }
  22169. // Shadows
  22170. if (scene.shadowsEnabled) {
  22171. var shadowGenerator = light.getShadowGenerator();
  22172. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22173. defines["SHADOW" + lightIndex] = true;
  22174. defines["SHADOWS"] = true;
  22175. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22176. defines["SHADOWVSM" + lightIndex] = true;
  22177. }
  22178. if (shadowGenerator.usePoissonSampling) {
  22179. defines["SHADOWPCF" + lightIndex] = true;
  22180. }
  22181. }
  22182. }
  22183. lightIndex++;
  22184. if (lightIndex === maxSimultaneousLights)
  22185. break;
  22186. }
  22187. return needNormals;
  22188. };
  22189. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  22190. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22191. if (!defines["LIGHT" + lightIndex]) {
  22192. continue;
  22193. }
  22194. if (lightIndex > 0) {
  22195. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22196. }
  22197. if (defines["SHADOW" + lightIndex]) {
  22198. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22199. }
  22200. if (defines["SHADOWPCF" + lightIndex]) {
  22201. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22202. }
  22203. if (defines["SHADOWVSM" + lightIndex]) {
  22204. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22205. }
  22206. }
  22207. };
  22208. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22209. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22210. fallbacks.addCPUSkinningFallback(0, mesh);
  22211. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22212. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22213. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22214. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22215. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22216. }
  22217. }
  22218. };
  22219. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22220. if (defines["INSTANCES"]) {
  22221. attribs.push("world0");
  22222. attribs.push("world1");
  22223. attribs.push("world2");
  22224. attribs.push("world3");
  22225. }
  22226. };
  22227. // Bindings
  22228. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22229. var shadowGenerator = light.getShadowGenerator();
  22230. if (mesh.receiveShadows && shadowGenerator) {
  22231. if (!light.needCube()) {
  22232. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22233. }
  22234. else {
  22235. if (!depthValuesAlreadySet) {
  22236. depthValuesAlreadySet = true;
  22237. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22238. }
  22239. }
  22240. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22241. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  22242. }
  22243. return depthValuesAlreadySet;
  22244. };
  22245. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22246. if (light instanceof BABYLON.PointLight) {
  22247. // Point Light
  22248. light.transferToEffect(effect, "vLightData" + lightIndex);
  22249. }
  22250. else if (light instanceof BABYLON.DirectionalLight) {
  22251. // Directional Light
  22252. light.transferToEffect(effect, "vLightData" + lightIndex);
  22253. }
  22254. else if (light instanceof BABYLON.SpotLight) {
  22255. // Spot Light
  22256. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22257. }
  22258. else if (light instanceof BABYLON.HemisphericLight) {
  22259. // Hemispheric Light
  22260. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22261. }
  22262. };
  22263. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  22264. var lightIndex = 0;
  22265. var depthValuesAlreadySet = false;
  22266. for (var index = 0; index < scene.lights.length; index++) {
  22267. var light = scene.lights[index];
  22268. if (!light.isEnabled()) {
  22269. continue;
  22270. }
  22271. if (!light.canAffectMesh(mesh)) {
  22272. continue;
  22273. }
  22274. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22275. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22276. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22277. if (defines["SPECULARTERM"]) {
  22278. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22279. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22280. }
  22281. // Shadows
  22282. if (scene.shadowsEnabled) {
  22283. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22284. }
  22285. lightIndex++;
  22286. if (lightIndex === maxSimultaneousLights)
  22287. break;
  22288. }
  22289. };
  22290. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22291. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22292. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22293. effect.setColor3("vFogColor", scene.fogColor);
  22294. }
  22295. };
  22296. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22297. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22298. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22299. }
  22300. };
  22301. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22302. if (defines["LOGARITHMICDEPTH"]) {
  22303. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22304. }
  22305. };
  22306. MaterialHelper.BindClipPlane = function (effect, scene) {
  22307. if (scene.clipPlane) {
  22308. var clipPlane = scene.clipPlane;
  22309. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22310. }
  22311. };
  22312. return MaterialHelper;
  22313. })();
  22314. BABYLON.MaterialHelper = MaterialHelper;
  22315. })(BABYLON || (BABYLON = {}));
  22316. var BABYLON;
  22317. (function (BABYLON) {
  22318. var FresnelParameters = (function () {
  22319. function FresnelParameters() {
  22320. this.isEnabled = true;
  22321. this.leftColor = BABYLON.Color3.White();
  22322. this.rightColor = BABYLON.Color3.Black();
  22323. this.bias = 0;
  22324. this.power = 1;
  22325. }
  22326. FresnelParameters.prototype.clone = function () {
  22327. var newFresnelParameters = new FresnelParameters();
  22328. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22329. return new FresnelParameters;
  22330. };
  22331. FresnelParameters.prototype.serialize = function () {
  22332. var serializationObject = {};
  22333. serializationObject.isEnabled = this.isEnabled;
  22334. serializationObject.leftColor = this.leftColor;
  22335. serializationObject.rightColor = this.rightColor;
  22336. serializationObject.bias = this.bias;
  22337. serializationObject.power = this.power;
  22338. return serializationObject;
  22339. };
  22340. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22341. var fresnelParameters = new FresnelParameters();
  22342. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22343. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22344. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22345. fresnelParameters.bias = parsedFresnelParameters.bias;
  22346. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22347. return fresnelParameters;
  22348. };
  22349. return FresnelParameters;
  22350. })();
  22351. BABYLON.FresnelParameters = FresnelParameters;
  22352. })(BABYLON || (BABYLON = {}));
  22353. var BABYLON;
  22354. (function (BABYLON) {
  22355. var MaterialDefines = (function () {
  22356. function MaterialDefines() {
  22357. }
  22358. MaterialDefines.prototype.isEqual = function (other) {
  22359. for (var index = 0; index < this._keys.length; index++) {
  22360. var prop = this._keys[index];
  22361. if (this[prop] !== other[prop]) {
  22362. return false;
  22363. }
  22364. }
  22365. return true;
  22366. };
  22367. MaterialDefines.prototype.cloneTo = function (other) {
  22368. for (var index = 0; index < this._keys.length; index++) {
  22369. var prop = this._keys[index];
  22370. other[prop] = this[prop];
  22371. }
  22372. };
  22373. MaterialDefines.prototype.reset = function () {
  22374. for (var index = 0; index < this._keys.length; index++) {
  22375. var prop = this._keys[index];
  22376. if (typeof (this[prop]) === "number") {
  22377. this[prop] = 0;
  22378. }
  22379. else {
  22380. this[prop] = false;
  22381. }
  22382. }
  22383. };
  22384. MaterialDefines.prototype.toString = function () {
  22385. var result = "";
  22386. for (var index = 0; index < this._keys.length; index++) {
  22387. var prop = this._keys[index];
  22388. if (typeof (this[prop]) === "number") {
  22389. result += "#define " + prop + " " + this[prop] + "\n";
  22390. }
  22391. else if (this[prop]) {
  22392. result += "#define " + prop + "\n";
  22393. }
  22394. }
  22395. return result;
  22396. };
  22397. return MaterialDefines;
  22398. })();
  22399. BABYLON.MaterialDefines = MaterialDefines;
  22400. var Material = (function () {
  22401. function Material(name, scene, doNotAdd) {
  22402. this.name = name;
  22403. this.checkReadyOnEveryCall = false;
  22404. this.checkReadyOnlyOnce = false;
  22405. this.state = "";
  22406. this.alpha = 1.0;
  22407. this.backFaceCulling = true;
  22408. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22409. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22410. this.disableDepthWrite = false;
  22411. this.fogEnabled = true;
  22412. this.pointSize = 1.0;
  22413. this.zOffset = 0;
  22414. this._wasPreviouslyReady = false;
  22415. this._fillMode = Material.TriangleFillMode;
  22416. this.id = name;
  22417. this._scene = scene;
  22418. if (!doNotAdd) {
  22419. scene.materials.push(this);
  22420. }
  22421. }
  22422. Object.defineProperty(Material, "TriangleFillMode", {
  22423. get: function () {
  22424. return Material._TriangleFillMode;
  22425. },
  22426. enumerable: true,
  22427. configurable: true
  22428. });
  22429. Object.defineProperty(Material, "WireFrameFillMode", {
  22430. get: function () {
  22431. return Material._WireFrameFillMode;
  22432. },
  22433. enumerable: true,
  22434. configurable: true
  22435. });
  22436. Object.defineProperty(Material, "PointFillMode", {
  22437. get: function () {
  22438. return Material._PointFillMode;
  22439. },
  22440. enumerable: true,
  22441. configurable: true
  22442. });
  22443. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22444. get: function () {
  22445. return Material._ClockWiseSideOrientation;
  22446. },
  22447. enumerable: true,
  22448. configurable: true
  22449. });
  22450. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22451. get: function () {
  22452. return Material._CounterClockWiseSideOrientation;
  22453. },
  22454. enumerable: true,
  22455. configurable: true
  22456. });
  22457. Object.defineProperty(Material.prototype, "wireframe", {
  22458. get: function () {
  22459. return this._fillMode === Material.WireFrameFillMode;
  22460. },
  22461. set: function (value) {
  22462. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22463. },
  22464. enumerable: true,
  22465. configurable: true
  22466. });
  22467. Object.defineProperty(Material.prototype, "pointsCloud", {
  22468. get: function () {
  22469. return this._fillMode === Material.PointFillMode;
  22470. },
  22471. set: function (value) {
  22472. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22473. },
  22474. enumerable: true,
  22475. configurable: true
  22476. });
  22477. Object.defineProperty(Material.prototype, "fillMode", {
  22478. get: function () {
  22479. return this._fillMode;
  22480. },
  22481. set: function (value) {
  22482. this._fillMode = value;
  22483. },
  22484. enumerable: true,
  22485. configurable: true
  22486. });
  22487. /**
  22488. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22489. * subclasses should override adding information pertainent to themselves
  22490. */
  22491. Material.prototype.toString = function (fullDetails) {
  22492. var ret = "Name: " + this.name;
  22493. if (fullDetails) {
  22494. }
  22495. return ret;
  22496. };
  22497. Object.defineProperty(Material.prototype, "isFrozen", {
  22498. get: function () {
  22499. return this.checkReadyOnlyOnce;
  22500. },
  22501. enumerable: true,
  22502. configurable: true
  22503. });
  22504. Material.prototype.freeze = function () {
  22505. this.checkReadyOnlyOnce = true;
  22506. };
  22507. Material.prototype.unfreeze = function () {
  22508. this.checkReadyOnlyOnce = false;
  22509. };
  22510. Material.prototype.isReady = function (mesh, useInstances) {
  22511. return true;
  22512. };
  22513. Material.prototype.getEffect = function () {
  22514. return this._effect;
  22515. };
  22516. Material.prototype.getScene = function () {
  22517. return this._scene;
  22518. };
  22519. Material.prototype.needAlphaBlending = function () {
  22520. return (this.alpha < 1.0);
  22521. };
  22522. Material.prototype.needAlphaTesting = function () {
  22523. return false;
  22524. };
  22525. Material.prototype.getAlphaTestTexture = function () {
  22526. return null;
  22527. };
  22528. Material.prototype.trackCreation = function (onCompiled, onError) {
  22529. };
  22530. Material.prototype.markDirty = function () {
  22531. this._wasPreviouslyReady = false;
  22532. };
  22533. Material.prototype._preBind = function () {
  22534. var engine = this._scene.getEngine();
  22535. engine.enableEffect(this._effect);
  22536. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  22537. };
  22538. Material.prototype.bind = function (world, mesh) {
  22539. this._scene._cachedMaterial = this;
  22540. if (this.onBind) {
  22541. this.onBind(this, mesh);
  22542. }
  22543. if (this.disableDepthWrite) {
  22544. var engine = this._scene.getEngine();
  22545. this._cachedDepthWriteState = engine.getDepthWrite();
  22546. engine.setDepthWrite(false);
  22547. }
  22548. };
  22549. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22550. };
  22551. Material.prototype.unbind = function () {
  22552. if (this.disableDepthWrite) {
  22553. var engine = this._scene.getEngine();
  22554. engine.setDepthWrite(this._cachedDepthWriteState);
  22555. }
  22556. };
  22557. Material.prototype.clone = function (name) {
  22558. return null;
  22559. };
  22560. Material.prototype.getBindedMeshes = function () {
  22561. var result = new Array();
  22562. for (var index = 0; index < this._scene.meshes.length; index++) {
  22563. var mesh = this._scene.meshes[index];
  22564. if (mesh.material === this) {
  22565. result.push(mesh);
  22566. }
  22567. }
  22568. return result;
  22569. };
  22570. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  22571. // Animations
  22572. this.getScene().stopAnimation(this);
  22573. // Remove from scene
  22574. var index = this._scene.materials.indexOf(this);
  22575. if (index >= 0) {
  22576. this._scene.materials.splice(index, 1);
  22577. }
  22578. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22579. if (forceDisposeEffect && this._effect) {
  22580. this._scene.getEngine()._releaseEffect(this._effect);
  22581. this._effect = null;
  22582. }
  22583. // Remove from meshes
  22584. for (index = 0; index < this._scene.meshes.length; index++) {
  22585. var mesh = this._scene.meshes[index];
  22586. if (mesh.material === this) {
  22587. mesh.material = null;
  22588. }
  22589. }
  22590. // Callback
  22591. if (this.onDispose) {
  22592. this.onDispose();
  22593. }
  22594. };
  22595. Material.prototype.serialize = function () {
  22596. return BABYLON.SerializationHelper.Serialize(this);
  22597. };
  22598. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22599. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22600. multiMaterial.id = parsedMultiMaterial.id;
  22601. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22602. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22603. var subMatId = parsedMultiMaterial.materials[matIndex];
  22604. if (subMatId) {
  22605. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22606. }
  22607. else {
  22608. multiMaterial.subMaterials.push(null);
  22609. }
  22610. }
  22611. return multiMaterial;
  22612. };
  22613. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22614. if (!parsedMaterial.customType) {
  22615. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22616. }
  22617. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22618. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22619. ;
  22620. };
  22621. Material._TriangleFillMode = 0;
  22622. Material._WireFrameFillMode = 1;
  22623. Material._PointFillMode = 2;
  22624. Material._ClockWiseSideOrientation = 0;
  22625. Material._CounterClockWiseSideOrientation = 1;
  22626. __decorate([
  22627. BABYLON.serialize()
  22628. ], Material.prototype, "id", void 0);
  22629. __decorate([
  22630. BABYLON.serialize()
  22631. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22632. __decorate([
  22633. BABYLON.serialize()
  22634. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22635. __decorate([
  22636. BABYLON.serialize()
  22637. ], Material.prototype, "state", void 0);
  22638. __decorate([
  22639. BABYLON.serialize()
  22640. ], Material.prototype, "alpha", void 0);
  22641. __decorate([
  22642. BABYLON.serialize()
  22643. ], Material.prototype, "backFaceCulling", void 0);
  22644. __decorate([
  22645. BABYLON.serialize()
  22646. ], Material.prototype, "sideOrientation", void 0);
  22647. __decorate([
  22648. BABYLON.serialize()
  22649. ], Material.prototype, "alphaMode", void 0);
  22650. __decorate([
  22651. BABYLON.serialize()
  22652. ], Material.prototype, "disableDepthWrite", void 0);
  22653. __decorate([
  22654. BABYLON.serialize()
  22655. ], Material.prototype, "fogEnabled", void 0);
  22656. __decorate([
  22657. BABYLON.serialize()
  22658. ], Material.prototype, "pointSize", void 0);
  22659. __decorate([
  22660. BABYLON.serialize()
  22661. ], Material.prototype, "zOffset", void 0);
  22662. __decorate([
  22663. BABYLON.serialize()
  22664. ], Material.prototype, "wireframe", null);
  22665. __decorate([
  22666. BABYLON.serialize()
  22667. ], Material.prototype, "pointsCloud", null);
  22668. __decorate([
  22669. BABYLON.serialize()
  22670. ], Material.prototype, "fillMode", null);
  22671. return Material;
  22672. })();
  22673. BABYLON.Material = Material;
  22674. })(BABYLON || (BABYLON = {}));
  22675. var BABYLON;
  22676. (function (BABYLON) {
  22677. var StandardMaterialDefines = (function (_super) {
  22678. __extends(StandardMaterialDefines, _super);
  22679. function StandardMaterialDefines() {
  22680. _super.call(this);
  22681. this.DIFFUSE = false;
  22682. this.AMBIENT = false;
  22683. this.OPACITY = false;
  22684. this.OPACITYRGB = false;
  22685. this.REFLECTION = false;
  22686. this.EMISSIVE = false;
  22687. this.SPECULAR = false;
  22688. this.BUMP = false;
  22689. this.PARALLAX = false;
  22690. this.PARALLAXOCCLUSION = false;
  22691. this.SPECULAROVERALPHA = false;
  22692. this.CLIPPLANE = false;
  22693. this.ALPHATEST = false;
  22694. this.ALPHAFROMDIFFUSE = false;
  22695. this.POINTSIZE = false;
  22696. this.FOG = false;
  22697. this.LIGHT0 = false;
  22698. this.LIGHT1 = false;
  22699. this.LIGHT2 = false;
  22700. this.LIGHT3 = false;
  22701. this.SPOTLIGHT0 = false;
  22702. this.SPOTLIGHT1 = false;
  22703. this.SPOTLIGHT2 = false;
  22704. this.SPOTLIGHT3 = false;
  22705. this.HEMILIGHT0 = false;
  22706. this.HEMILIGHT1 = false;
  22707. this.HEMILIGHT2 = false;
  22708. this.HEMILIGHT3 = false;
  22709. this.POINTLIGHT0 = false;
  22710. this.POINTLIGHT1 = false;
  22711. this.POINTLIGHT2 = false;
  22712. this.POINTLIGHT3 = false;
  22713. this.DIRLIGHT0 = false;
  22714. this.DIRLIGHT1 = false;
  22715. this.DIRLIGHT2 = false;
  22716. this.DIRLIGHT3 = false;
  22717. this.SPECULARTERM = false;
  22718. this.SHADOW0 = false;
  22719. this.SHADOW1 = false;
  22720. this.SHADOW2 = false;
  22721. this.SHADOW3 = false;
  22722. this.SHADOWS = false;
  22723. this.SHADOWVSM0 = false;
  22724. this.SHADOWVSM1 = false;
  22725. this.SHADOWVSM2 = false;
  22726. this.SHADOWVSM3 = false;
  22727. this.SHADOWPCF0 = false;
  22728. this.SHADOWPCF1 = false;
  22729. this.SHADOWPCF2 = false;
  22730. this.SHADOWPCF3 = false;
  22731. this.DIFFUSEFRESNEL = false;
  22732. this.OPACITYFRESNEL = false;
  22733. this.REFLECTIONFRESNEL = false;
  22734. this.REFRACTIONFRESNEL = false;
  22735. this.EMISSIVEFRESNEL = false;
  22736. this.FRESNEL = false;
  22737. this.NORMAL = false;
  22738. this.UV1 = false;
  22739. this.UV2 = false;
  22740. this.VERTEXCOLOR = false;
  22741. this.VERTEXALPHA = false;
  22742. this.NUM_BONE_INFLUENCERS = 0;
  22743. this.BonesPerMesh = 0;
  22744. this.INSTANCES = false;
  22745. this.GLOSSINESS = false;
  22746. this.ROUGHNESS = false;
  22747. this.EMISSIVEASILLUMINATION = false;
  22748. this.LINKEMISSIVEWITHDIFFUSE = false;
  22749. this.REFLECTIONFRESNELFROMSPECULAR = false;
  22750. this.LIGHTMAP = false;
  22751. this.USELIGHTMAPASSHADOWMAP = false;
  22752. this.REFLECTIONMAP_3D = false;
  22753. this.REFLECTIONMAP_SPHERICAL = false;
  22754. this.REFLECTIONMAP_PLANAR = false;
  22755. this.REFLECTIONMAP_CUBIC = false;
  22756. this.REFLECTIONMAP_PROJECTION = false;
  22757. this.REFLECTIONMAP_SKYBOX = false;
  22758. this.REFLECTIONMAP_EXPLICIT = false;
  22759. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  22760. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  22761. this.INVERTCUBICMAP = false;
  22762. this.LOGARITHMICDEPTH = false;
  22763. this.REFRACTION = false;
  22764. this.REFRACTIONMAP_3D = false;
  22765. this.REFLECTIONOVERALPHA = false;
  22766. this._keys = Object.keys(this);
  22767. }
  22768. return StandardMaterialDefines;
  22769. })(BABYLON.MaterialDefines);
  22770. var StandardMaterial = (function (_super) {
  22771. __extends(StandardMaterial, _super);
  22772. function StandardMaterial(name, scene) {
  22773. var _this = this;
  22774. _super.call(this, name, scene);
  22775. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22776. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  22777. this.specularColor = new BABYLON.Color3(1, 1, 1);
  22778. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  22779. this.specularPower = 64;
  22780. this.useAlphaFromDiffuseTexture = false;
  22781. this.useEmissiveAsIllumination = false;
  22782. this.linkEmissiveWithDiffuse = false;
  22783. this.useReflectionFresnelFromSpecular = false;
  22784. this.useSpecularOverAlpha = false;
  22785. this.useReflectionOverAlpha = false;
  22786. this.disableLighting = false;
  22787. this.useParallax = false;
  22788. this.useParallaxOcclusion = false;
  22789. this.parallaxScaleBias = 0.05;
  22790. this.roughness = 0;
  22791. this.indexOfRefraction = 0.98;
  22792. this.invertRefractionY = true;
  22793. this.useLightmapAsShadowmap = false;
  22794. this.useGlossinessFromSpecularMapAlpha = false;
  22795. this._renderTargets = new BABYLON.SmartArray(16);
  22796. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  22797. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  22798. this._defines = new StandardMaterialDefines();
  22799. this._cachedDefines = new StandardMaterialDefines();
  22800. this._cachedDefines.BonesPerMesh = -1;
  22801. this.getRenderTargetTextures = function () {
  22802. _this._renderTargets.reset();
  22803. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  22804. _this._renderTargets.push(_this.reflectionTexture);
  22805. }
  22806. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  22807. _this._renderTargets.push(_this.refractionTexture);
  22808. }
  22809. return _this._renderTargets;
  22810. };
  22811. }
  22812. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  22813. get: function () {
  22814. return this._useLogarithmicDepth;
  22815. },
  22816. set: function (value) {
  22817. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  22818. },
  22819. enumerable: true,
  22820. configurable: true
  22821. });
  22822. StandardMaterial.prototype.needAlphaBlending = function () {
  22823. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  22824. };
  22825. StandardMaterial.prototype.needAlphaTesting = function () {
  22826. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  22827. };
  22828. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  22829. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  22830. };
  22831. StandardMaterial.prototype.getAlphaTestTexture = function () {
  22832. return this.diffuseTexture;
  22833. };
  22834. // Methods
  22835. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  22836. if (!mesh) {
  22837. return true;
  22838. }
  22839. if (this._defines.INSTANCES !== useInstances) {
  22840. return false;
  22841. }
  22842. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  22843. return true;
  22844. }
  22845. return false;
  22846. };
  22847. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  22848. if (this.isFrozen) {
  22849. if (this._wasPreviouslyReady) {
  22850. return true;
  22851. }
  22852. }
  22853. var scene = this.getScene();
  22854. if (!this.checkReadyOnEveryCall) {
  22855. if (this._renderId === scene.getRenderId()) {
  22856. if (this._checkCache(scene, mesh, useInstances)) {
  22857. return true;
  22858. }
  22859. }
  22860. }
  22861. var engine = scene.getEngine();
  22862. var needNormals = false;
  22863. var needUVs = false;
  22864. this._defines.reset();
  22865. // Textures
  22866. if (scene.texturesEnabled) {
  22867. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22868. if (!this.diffuseTexture.isReady()) {
  22869. return false;
  22870. }
  22871. else {
  22872. needUVs = true;
  22873. this._defines.DIFFUSE = true;
  22874. }
  22875. }
  22876. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22877. if (!this.ambientTexture.isReady()) {
  22878. return false;
  22879. }
  22880. else {
  22881. needUVs = true;
  22882. this._defines.AMBIENT = true;
  22883. }
  22884. }
  22885. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22886. if (!this.opacityTexture.isReady()) {
  22887. return false;
  22888. }
  22889. else {
  22890. needUVs = true;
  22891. this._defines.OPACITY = true;
  22892. if (this.opacityTexture.getAlphaFromRGB) {
  22893. this._defines.OPACITYRGB = true;
  22894. }
  22895. }
  22896. }
  22897. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22898. if (!this.reflectionTexture.isReady()) {
  22899. return false;
  22900. }
  22901. else {
  22902. needNormals = true;
  22903. this._defines.REFLECTION = true;
  22904. if (this.roughness > 0) {
  22905. this._defines.ROUGHNESS = true;
  22906. }
  22907. if (this.useReflectionOverAlpha) {
  22908. this._defines.REFLECTIONOVERALPHA = true;
  22909. }
  22910. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  22911. this._defines.INVERTCUBICMAP = true;
  22912. }
  22913. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  22914. switch (this.reflectionTexture.coordinatesMode) {
  22915. case BABYLON.Texture.CUBIC_MODE:
  22916. case BABYLON.Texture.INVCUBIC_MODE:
  22917. this._defines.REFLECTIONMAP_CUBIC = true;
  22918. break;
  22919. case BABYLON.Texture.EXPLICIT_MODE:
  22920. this._defines.REFLECTIONMAP_EXPLICIT = true;
  22921. break;
  22922. case BABYLON.Texture.PLANAR_MODE:
  22923. this._defines.REFLECTIONMAP_PLANAR = true;
  22924. break;
  22925. case BABYLON.Texture.PROJECTION_MODE:
  22926. this._defines.REFLECTIONMAP_PROJECTION = true;
  22927. break;
  22928. case BABYLON.Texture.SKYBOX_MODE:
  22929. this._defines.REFLECTIONMAP_SKYBOX = true;
  22930. break;
  22931. case BABYLON.Texture.SPHERICAL_MODE:
  22932. this._defines.REFLECTIONMAP_SPHERICAL = true;
  22933. break;
  22934. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  22935. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  22936. break;
  22937. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  22938. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  22939. break;
  22940. }
  22941. }
  22942. }
  22943. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  22944. if (!this.emissiveTexture.isReady()) {
  22945. return false;
  22946. }
  22947. else {
  22948. needUVs = true;
  22949. this._defines.EMISSIVE = true;
  22950. }
  22951. }
  22952. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  22953. if (!this.lightmapTexture.isReady()) {
  22954. return false;
  22955. }
  22956. else {
  22957. needUVs = true;
  22958. this._defines.LIGHTMAP = true;
  22959. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  22960. }
  22961. }
  22962. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  22963. if (!this.specularTexture.isReady()) {
  22964. return false;
  22965. }
  22966. else {
  22967. needUVs = true;
  22968. this._defines.SPECULAR = true;
  22969. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  22970. }
  22971. }
  22972. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  22973. if (!this.bumpTexture.isReady()) {
  22974. return false;
  22975. }
  22976. else {
  22977. needUVs = true;
  22978. this._defines.BUMP = true;
  22979. if (this.useParallax) {
  22980. this._defines.PARALLAX = true;
  22981. if (this.useParallaxOcclusion) {
  22982. this._defines.PARALLAXOCCLUSION = true;
  22983. }
  22984. }
  22985. }
  22986. }
  22987. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  22988. if (!this.refractionTexture.isReady()) {
  22989. return false;
  22990. }
  22991. else {
  22992. needUVs = true;
  22993. this._defines.REFRACTION = true;
  22994. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  22995. }
  22996. }
  22997. }
  22998. // Effect
  22999. if (scene.clipPlane) {
  23000. this._defines.CLIPPLANE = true;
  23001. }
  23002. if (engine.getAlphaTesting()) {
  23003. this._defines.ALPHATEST = true;
  23004. }
  23005. if (this._shouldUseAlphaFromDiffuseTexture()) {
  23006. this._defines.ALPHAFROMDIFFUSE = true;
  23007. }
  23008. if (this.useEmissiveAsIllumination) {
  23009. this._defines.EMISSIVEASILLUMINATION = true;
  23010. }
  23011. if (this.linkEmissiveWithDiffuse) {
  23012. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  23013. }
  23014. if (this.useLogarithmicDepth) {
  23015. this._defines.LOGARITHMICDEPTH = true;
  23016. }
  23017. // Point size
  23018. if (this.pointsCloud || scene.forcePointsCloud) {
  23019. this._defines.POINTSIZE = true;
  23020. }
  23021. // Fog
  23022. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23023. this._defines.FOG = true;
  23024. }
  23025. if (scene.lightsEnabled && !this.disableLighting) {
  23026. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  23027. }
  23028. if (StandardMaterial.FresnelEnabled) {
  23029. // Fresnel
  23030. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  23031. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  23032. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  23033. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  23034. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23035. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23036. this._defines.DIFFUSEFRESNEL = true;
  23037. }
  23038. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23039. this._defines.OPACITYFRESNEL = true;
  23040. }
  23041. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23042. this._defines.REFLECTIONFRESNEL = true;
  23043. if (this.useReflectionFresnelFromSpecular) {
  23044. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  23045. }
  23046. }
  23047. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23048. this._defines.REFRACTIONFRESNEL = true;
  23049. }
  23050. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23051. this._defines.EMISSIVEFRESNEL = true;
  23052. }
  23053. needNormals = true;
  23054. this._defines.FRESNEL = true;
  23055. }
  23056. }
  23057. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  23058. this._defines.SPECULAROVERALPHA = true;
  23059. }
  23060. // Attribs
  23061. if (mesh) {
  23062. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23063. this._defines.NORMAL = true;
  23064. }
  23065. if (needUVs) {
  23066. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23067. this._defines.UV1 = true;
  23068. }
  23069. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23070. this._defines.UV2 = true;
  23071. }
  23072. }
  23073. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23074. this._defines.VERTEXCOLOR = true;
  23075. if (mesh.hasVertexAlpha) {
  23076. this._defines.VERTEXALPHA = true;
  23077. }
  23078. }
  23079. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23080. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  23081. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  23082. }
  23083. // Instances
  23084. if (useInstances) {
  23085. this._defines.INSTANCES = true;
  23086. }
  23087. }
  23088. // Get correct effect
  23089. if (!this._defines.isEqual(this._cachedDefines)) {
  23090. this._defines.cloneTo(this._cachedDefines);
  23091. scene.resetCachedMaterial();
  23092. // Fallbacks
  23093. var fallbacks = new BABYLON.EffectFallbacks();
  23094. if (this._defines.REFLECTION) {
  23095. fallbacks.addFallback(0, "REFLECTION");
  23096. }
  23097. if (this._defines.SPECULAR) {
  23098. fallbacks.addFallback(0, "SPECULAR");
  23099. }
  23100. if (this._defines.BUMP) {
  23101. fallbacks.addFallback(0, "BUMP");
  23102. }
  23103. if (this._defines.PARALLAX) {
  23104. fallbacks.addFallback(1, "PARALLAX");
  23105. }
  23106. if (this._defines.PARALLAXOCCLUSION) {
  23107. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  23108. }
  23109. if (this._defines.SPECULAROVERALPHA) {
  23110. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  23111. }
  23112. if (this._defines.FOG) {
  23113. fallbacks.addFallback(1, "FOG");
  23114. }
  23115. if (this._defines.POINTSIZE) {
  23116. fallbacks.addFallback(0, "POINTSIZE");
  23117. }
  23118. if (this._defines.LOGARITHMICDEPTH) {
  23119. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  23120. }
  23121. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  23122. if (this._defines.SPECULARTERM) {
  23123. fallbacks.addFallback(0, "SPECULARTERM");
  23124. }
  23125. if (this._defines.DIFFUSEFRESNEL) {
  23126. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  23127. }
  23128. if (this._defines.OPACITYFRESNEL) {
  23129. fallbacks.addFallback(2, "OPACITYFRESNEL");
  23130. }
  23131. if (this._defines.REFLECTIONFRESNEL) {
  23132. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  23133. }
  23134. if (this._defines.EMISSIVEFRESNEL) {
  23135. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  23136. }
  23137. if (this._defines.FRESNEL) {
  23138. fallbacks.addFallback(4, "FRESNEL");
  23139. }
  23140. //Attributes
  23141. var attribs = [BABYLON.VertexBuffer.PositionKind];
  23142. if (this._defines.NORMAL) {
  23143. attribs.push(BABYLON.VertexBuffer.NormalKind);
  23144. }
  23145. if (this._defines.UV1) {
  23146. attribs.push(BABYLON.VertexBuffer.UVKind);
  23147. }
  23148. if (this._defines.UV2) {
  23149. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23150. }
  23151. if (this._defines.VERTEXCOLOR) {
  23152. attribs.push(BABYLON.VertexBuffer.ColorKind);
  23153. }
  23154. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  23155. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  23156. // Legacy browser patch
  23157. var shaderName = "default";
  23158. if (!scene.getEngine().getCaps().standardDerivatives) {
  23159. shaderName = "legacydefault";
  23160. }
  23161. var join = this._defines.toString();
  23162. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  23163. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  23164. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  23165. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  23166. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  23167. "vFogInfos", "vFogColor", "pointSize",
  23168. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  23169. "mBones",
  23170. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  23171. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  23172. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  23173. "logarithmicDepthConstant"
  23174. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  23175. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  23176. ], join, fallbacks, this.onCompiled, this.onError);
  23177. }
  23178. if (!this._effect.isReady()) {
  23179. return false;
  23180. }
  23181. this._renderId = scene.getRenderId();
  23182. this._wasPreviouslyReady = true;
  23183. if (mesh) {
  23184. if (!mesh._materialDefines) {
  23185. mesh._materialDefines = new StandardMaterialDefines();
  23186. }
  23187. this._defines.cloneTo(mesh._materialDefines);
  23188. }
  23189. return true;
  23190. };
  23191. StandardMaterial.prototype.unbind = function () {
  23192. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23193. this._effect.setTexture("reflection2DSampler", null);
  23194. }
  23195. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23196. this._effect.setTexture("refraction2DSampler", null);
  23197. }
  23198. _super.prototype.unbind.call(this);
  23199. };
  23200. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23201. this._effect.setMatrix("world", world);
  23202. };
  23203. StandardMaterial.prototype.bind = function (world, mesh) {
  23204. var scene = this.getScene();
  23205. // Matrices
  23206. this.bindOnlyWorldMatrix(world);
  23207. // Bones
  23208. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  23209. if (scene.getCachedMaterial() !== this) {
  23210. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23211. if (StandardMaterial.FresnelEnabled) {
  23212. // Fresnel
  23213. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23214. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  23215. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  23216. }
  23217. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23218. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  23219. }
  23220. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23221. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  23222. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  23223. }
  23224. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23225. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  23226. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  23227. }
  23228. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23229. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  23230. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  23231. }
  23232. }
  23233. // Textures
  23234. if (scene.texturesEnabled) {
  23235. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23236. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  23237. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  23238. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  23239. }
  23240. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23241. this._effect.setTexture("ambientSampler", this.ambientTexture);
  23242. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  23243. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  23244. }
  23245. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23246. this._effect.setTexture("opacitySampler", this.opacityTexture);
  23247. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  23248. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  23249. }
  23250. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23251. if (this.reflectionTexture.isCube) {
  23252. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  23253. }
  23254. else {
  23255. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  23256. }
  23257. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  23258. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23259. }
  23260. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23261. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23262. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23263. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23264. }
  23265. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23266. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23267. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23268. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23269. }
  23270. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23271. this._effect.setTexture("specularSampler", this.specularTexture);
  23272. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23273. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23274. }
  23275. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23276. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23277. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23278. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23279. }
  23280. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23281. var depth = 1.0;
  23282. if (this.refractionTexture.isCube) {
  23283. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23284. }
  23285. else {
  23286. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23287. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23288. if (this.refractionTexture.depth) {
  23289. depth = this.refractionTexture.depth;
  23290. }
  23291. }
  23292. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23293. }
  23294. }
  23295. // Clip plane
  23296. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23297. // Point size
  23298. if (this.pointsCloud) {
  23299. this._effect.setFloat("pointSize", this.pointSize);
  23300. }
  23301. // Colors
  23302. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23303. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23304. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23305. if (this._defines.SPECULARTERM) {
  23306. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23307. }
  23308. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23309. }
  23310. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23311. // Diffuse
  23312. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23313. // Lights
  23314. if (scene.lightsEnabled && !this.disableLighting) {
  23315. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  23316. }
  23317. // View
  23318. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23319. this._effect.setMatrix("view", scene.getViewMatrix());
  23320. }
  23321. // Fog
  23322. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23323. // Log. depth
  23324. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23325. }
  23326. _super.prototype.bind.call(this, world, mesh);
  23327. };
  23328. StandardMaterial.prototype.getAnimatables = function () {
  23329. var results = [];
  23330. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23331. results.push(this.diffuseTexture);
  23332. }
  23333. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23334. results.push(this.ambientTexture);
  23335. }
  23336. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23337. results.push(this.opacityTexture);
  23338. }
  23339. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23340. results.push(this.reflectionTexture);
  23341. }
  23342. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23343. results.push(this.emissiveTexture);
  23344. }
  23345. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23346. results.push(this.specularTexture);
  23347. }
  23348. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23349. results.push(this.bumpTexture);
  23350. }
  23351. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23352. results.push(this.lightmapTexture);
  23353. }
  23354. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23355. results.push(this.refractionTexture);
  23356. }
  23357. return results;
  23358. };
  23359. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23360. if (forceDisposeTextures) {
  23361. if (this.diffuseTexture) {
  23362. this.diffuseTexture.dispose();
  23363. }
  23364. if (this.ambientTexture) {
  23365. this.ambientTexture.dispose();
  23366. }
  23367. if (this.opacityTexture) {
  23368. this.opacityTexture.dispose();
  23369. }
  23370. if (this.reflectionTexture) {
  23371. this.reflectionTexture.dispose();
  23372. }
  23373. if (this.emissiveTexture) {
  23374. this.emissiveTexture.dispose();
  23375. }
  23376. if (this.specularTexture) {
  23377. this.specularTexture.dispose();
  23378. }
  23379. if (this.bumpTexture) {
  23380. this.bumpTexture.dispose();
  23381. }
  23382. if (this.lightmapTexture) {
  23383. this.lightmapTexture.dispose();
  23384. }
  23385. if (this.refractionTexture) {
  23386. this.refractionTexture.dispose();
  23387. }
  23388. }
  23389. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  23390. };
  23391. StandardMaterial.prototype.clone = function (name) {
  23392. var _this = this;
  23393. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23394. };
  23395. StandardMaterial.prototype.serialize = function () {
  23396. return BABYLON.SerializationHelper.Serialize(this);
  23397. };
  23398. // Statics
  23399. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23400. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23401. };
  23402. // Flags used to enable or disable a type of texture for all Standard Materials
  23403. StandardMaterial.DiffuseTextureEnabled = true;
  23404. StandardMaterial.AmbientTextureEnabled = true;
  23405. StandardMaterial.OpacityTextureEnabled = true;
  23406. StandardMaterial.ReflectionTextureEnabled = true;
  23407. StandardMaterial.EmissiveTextureEnabled = true;
  23408. StandardMaterial.SpecularTextureEnabled = true;
  23409. StandardMaterial.BumpTextureEnabled = true;
  23410. StandardMaterial.FresnelEnabled = true;
  23411. StandardMaterial.LightmapTextureEnabled = true;
  23412. StandardMaterial.RefractionTextureEnabled = true;
  23413. __decorate([
  23414. BABYLON.serializeAsTexture()
  23415. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23416. __decorate([
  23417. BABYLON.serializeAsTexture()
  23418. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23419. __decorate([
  23420. BABYLON.serializeAsTexture()
  23421. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23422. __decorate([
  23423. BABYLON.serializeAsTexture()
  23424. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23425. __decorate([
  23426. BABYLON.serializeAsTexture()
  23427. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23428. __decorate([
  23429. BABYLON.serializeAsTexture()
  23430. ], StandardMaterial.prototype, "specularTexture", void 0);
  23431. __decorate([
  23432. BABYLON.serializeAsTexture()
  23433. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23434. __decorate([
  23435. BABYLON.serializeAsTexture()
  23436. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23437. __decorate([
  23438. BABYLON.serializeAsTexture()
  23439. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23440. __decorate([
  23441. BABYLON.serializeAsColor3("ambient")
  23442. ], StandardMaterial.prototype, "ambientColor", void 0);
  23443. __decorate([
  23444. BABYLON.serializeAsColor3("diffuse")
  23445. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23446. __decorate([
  23447. BABYLON.serializeAsColor3("specular")
  23448. ], StandardMaterial.prototype, "specularColor", void 0);
  23449. __decorate([
  23450. BABYLON.serializeAsColor3("emissive")
  23451. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23452. __decorate([
  23453. BABYLON.serialize()
  23454. ], StandardMaterial.prototype, "specularPower", void 0);
  23455. __decorate([
  23456. BABYLON.serialize()
  23457. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23458. __decorate([
  23459. BABYLON.serialize()
  23460. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23461. __decorate([
  23462. BABYLON.serialize()
  23463. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23464. __decorate([
  23465. BABYLON.serialize()
  23466. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23467. __decorate([
  23468. BABYLON.serialize()
  23469. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23470. __decorate([
  23471. BABYLON.serialize()
  23472. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23473. __decorate([
  23474. BABYLON.serialize()
  23475. ], StandardMaterial.prototype, "disableLighting", void 0);
  23476. __decorate([
  23477. BABYLON.serialize()
  23478. ], StandardMaterial.prototype, "useParallax", void 0);
  23479. __decorate([
  23480. BABYLON.serialize()
  23481. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23482. __decorate([
  23483. BABYLON.serialize()
  23484. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23485. __decorate([
  23486. BABYLON.serialize()
  23487. ], StandardMaterial.prototype, "roughness", void 0);
  23488. __decorate([
  23489. BABYLON.serialize()
  23490. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23491. __decorate([
  23492. BABYLON.serialize()
  23493. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23494. __decorate([
  23495. BABYLON.serialize()
  23496. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23497. __decorate([
  23498. BABYLON.serializeAsFresnelParameters()
  23499. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23500. __decorate([
  23501. BABYLON.serializeAsFresnelParameters()
  23502. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23503. __decorate([
  23504. BABYLON.serializeAsFresnelParameters()
  23505. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23506. __decorate([
  23507. BABYLON.serializeAsFresnelParameters()
  23508. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  23509. __decorate([
  23510. BABYLON.serializeAsFresnelParameters()
  23511. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  23512. __decorate([
  23513. BABYLON.serialize()
  23514. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  23515. __decorate([
  23516. BABYLON.serialize()
  23517. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  23518. return StandardMaterial;
  23519. })(BABYLON.Material);
  23520. BABYLON.StandardMaterial = StandardMaterial;
  23521. })(BABYLON || (BABYLON = {}));
  23522. var BABYLON;
  23523. (function (BABYLON) {
  23524. var MultiMaterial = (function (_super) {
  23525. __extends(MultiMaterial, _super);
  23526. function MultiMaterial(name, scene) {
  23527. _super.call(this, name, scene, true);
  23528. this.subMaterials = new Array();
  23529. scene.multiMaterials.push(this);
  23530. }
  23531. // Properties
  23532. MultiMaterial.prototype.getSubMaterial = function (index) {
  23533. if (index < 0 || index >= this.subMaterials.length) {
  23534. return this.getScene().defaultMaterial;
  23535. }
  23536. return this.subMaterials[index];
  23537. };
  23538. // Methods
  23539. MultiMaterial.prototype.isReady = function (mesh) {
  23540. for (var index = 0; index < this.subMaterials.length; index++) {
  23541. var subMaterial = this.subMaterials[index];
  23542. if (subMaterial) {
  23543. if (!this.subMaterials[index].isReady(mesh)) {
  23544. return false;
  23545. }
  23546. }
  23547. }
  23548. return true;
  23549. };
  23550. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  23551. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  23552. for (var index = 0; index < this.subMaterials.length; index++) {
  23553. var subMaterial = null;
  23554. if (cloneChildren) {
  23555. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  23556. }
  23557. else {
  23558. subMaterial = this.subMaterials[index];
  23559. }
  23560. newMultiMaterial.subMaterials.push(subMaterial);
  23561. }
  23562. return newMultiMaterial;
  23563. };
  23564. MultiMaterial.prototype.serialize = function () {
  23565. var serializationObject = {};
  23566. serializationObject.name = this.name;
  23567. serializationObject.id = this.id;
  23568. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23569. serializationObject.materials = [];
  23570. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  23571. var subMat = this.subMaterials[matIndex];
  23572. if (subMat) {
  23573. serializationObject.materials.push(subMat.id);
  23574. }
  23575. else {
  23576. serializationObject.materials.push(null);
  23577. }
  23578. }
  23579. return serializationObject;
  23580. };
  23581. return MultiMaterial;
  23582. })(BABYLON.Material);
  23583. BABYLON.MultiMaterial = MultiMaterial;
  23584. })(BABYLON || (BABYLON = {}));
  23585. var BABYLON;
  23586. (function (BABYLON) {
  23587. var SceneLoader = (function () {
  23588. function SceneLoader() {
  23589. }
  23590. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  23591. get: function () {
  23592. return 0;
  23593. },
  23594. enumerable: true,
  23595. configurable: true
  23596. });
  23597. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  23598. get: function () {
  23599. return 1;
  23600. },
  23601. enumerable: true,
  23602. configurable: true
  23603. });
  23604. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  23605. get: function () {
  23606. return 2;
  23607. },
  23608. enumerable: true,
  23609. configurable: true
  23610. });
  23611. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  23612. get: function () {
  23613. return 3;
  23614. },
  23615. enumerable: true,
  23616. configurable: true
  23617. });
  23618. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  23619. get: function () {
  23620. return SceneLoader._ForceFullSceneLoadingForIncremental;
  23621. },
  23622. set: function (value) {
  23623. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  23624. },
  23625. enumerable: true,
  23626. configurable: true
  23627. });
  23628. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  23629. get: function () {
  23630. return SceneLoader._ShowLoadingScreen;
  23631. },
  23632. set: function (value) {
  23633. SceneLoader._ShowLoadingScreen = value;
  23634. },
  23635. enumerable: true,
  23636. configurable: true
  23637. });
  23638. Object.defineProperty(SceneLoader, "loggingLevel", {
  23639. get: function () {
  23640. return SceneLoader._loggingLevel;
  23641. },
  23642. set: function (value) {
  23643. SceneLoader._loggingLevel = value;
  23644. },
  23645. enumerable: true,
  23646. configurable: true
  23647. });
  23648. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23649. var dotPosition = sceneFilename.lastIndexOf(".");
  23650. var queryStringPosition = sceneFilename.indexOf("?");
  23651. if (queryStringPosition === -1) {
  23652. queryStringPosition = sceneFilename.length;
  23653. }
  23654. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23655. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23656. var plugin = this._registeredPlugins[index];
  23657. if (plugin.extensions.indexOf(extension) !== -1) {
  23658. return plugin;
  23659. }
  23660. }
  23661. return this._registeredPlugins[0];
  23662. };
  23663. // Public functions
  23664. SceneLoader.GetPluginForExtension = function (extension) {
  23665. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23666. var plugin = this._registeredPlugins[index];
  23667. if (plugin.extensions.indexOf(extension) !== -1) {
  23668. return plugin;
  23669. }
  23670. }
  23671. return null;
  23672. };
  23673. SceneLoader.RegisterPlugin = function (plugin) {
  23674. plugin.extensions = plugin.extensions.toLowerCase();
  23675. SceneLoader._registeredPlugins.push(plugin);
  23676. };
  23677. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23678. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23679. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23680. return;
  23681. }
  23682. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23683. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23684. return;
  23685. }
  23686. var loadingToken = {};
  23687. scene._addPendingData(loadingToken);
  23688. var manifestChecked = function (success) {
  23689. scene.database = database;
  23690. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  23691. var importMeshFromData = function (data) {
  23692. var meshes = [];
  23693. var particleSystems = [];
  23694. var skeletons = [];
  23695. try {
  23696. if (plugin.importMesh) {
  23697. var syncedPlugin = plugin;
  23698. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  23699. if (onerror) {
  23700. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23701. }
  23702. scene._removePendingData(loadingToken);
  23703. return;
  23704. }
  23705. if (onsuccess) {
  23706. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23707. onsuccess(meshes, particleSystems, skeletons);
  23708. scene._removePendingData(loadingToken);
  23709. }
  23710. }
  23711. else {
  23712. var asyncedPlugin = plugin;
  23713. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  23714. if (onsuccess) {
  23715. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23716. onsuccess(meshes, particleSystems, skeletons);
  23717. scene._removePendingData(loadingToken);
  23718. }
  23719. }, function () {
  23720. if (onerror) {
  23721. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23722. }
  23723. scene._removePendingData(loadingToken);
  23724. });
  23725. }
  23726. }
  23727. catch (e) {
  23728. if (onerror) {
  23729. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  23730. }
  23731. scene._removePendingData(loadingToken);
  23732. }
  23733. };
  23734. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23735. // Direct load
  23736. importMeshFromData(sceneFilename.substr(5));
  23737. return;
  23738. }
  23739. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  23740. importMeshFromData(data);
  23741. }, progressCallBack, database);
  23742. };
  23743. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  23744. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23745. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23746. }
  23747. else {
  23748. // If the scene is a data stream or offline support is not enabled, it's a direct load
  23749. manifestChecked(true);
  23750. }
  23751. };
  23752. /**
  23753. * Load a scene
  23754. * @param rootUrl a string that defines the root url for scene and resources
  23755. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23756. * @param engine is the instance of BABYLON.Engine to use to create the scene
  23757. */
  23758. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  23759. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  23760. };
  23761. /**
  23762. * Append a scene
  23763. * @param rootUrl a string that defines the root url for scene and resources
  23764. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23765. * @param scene is the instance of BABYLON.Scene to append to
  23766. */
  23767. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23768. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23769. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23770. return;
  23771. }
  23772. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  23773. var database;
  23774. var loadingToken = {};
  23775. scene._addPendingData(loadingToken);
  23776. if (SceneLoader.ShowLoadingScreen) {
  23777. scene.getEngine().displayLoadingUI();
  23778. }
  23779. var loadSceneFromData = function (data) {
  23780. scene.database = database;
  23781. if (plugin.load) {
  23782. var syncedPlugin = plugin;
  23783. if (!syncedPlugin.load(scene, data, rootUrl)) {
  23784. if (onerror) {
  23785. onerror(scene);
  23786. }
  23787. scene._removePendingData(loadingToken);
  23788. scene.getEngine().hideLoadingUI();
  23789. return;
  23790. }
  23791. if (onsuccess) {
  23792. onsuccess(scene);
  23793. }
  23794. scene._removePendingData(loadingToken);
  23795. }
  23796. else {
  23797. var asyncedPlugin = plugin;
  23798. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  23799. if (onsuccess) {
  23800. onsuccess(scene);
  23801. }
  23802. }, function () {
  23803. if (onerror) {
  23804. onerror(scene);
  23805. }
  23806. scene._removePendingData(loadingToken);
  23807. scene.getEngine().hideLoadingUI();
  23808. });
  23809. }
  23810. if (SceneLoader.ShowLoadingScreen) {
  23811. scene.executeWhenReady(function () {
  23812. scene.getEngine().hideLoadingUI();
  23813. });
  23814. }
  23815. };
  23816. var manifestChecked = function (success) {
  23817. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  23818. };
  23819. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23820. // Direct load
  23821. loadSceneFromData(sceneFilename.substr(5));
  23822. return;
  23823. }
  23824. if (rootUrl.indexOf("file:") === -1) {
  23825. if (scene.getEngine().enableOfflineSupport) {
  23826. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23827. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23828. }
  23829. else {
  23830. manifestChecked(true);
  23831. }
  23832. }
  23833. else {
  23834. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  23835. }
  23836. };
  23837. // Flags
  23838. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  23839. SceneLoader._ShowLoadingScreen = true;
  23840. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  23841. // Members
  23842. SceneLoader._registeredPlugins = new Array();
  23843. return SceneLoader;
  23844. })();
  23845. BABYLON.SceneLoader = SceneLoader;
  23846. ;
  23847. })(BABYLON || (BABYLON = {}));
  23848. var BABYLON;
  23849. (function (BABYLON) {
  23850. var Internals;
  23851. (function (Internals) {
  23852. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  23853. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23854. var parsedMaterial = parsedData.materials[index];
  23855. if (parsedMaterial.id === id) {
  23856. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23857. }
  23858. }
  23859. return null;
  23860. };
  23861. var isDescendantOf = function (mesh, names, hierarchyIds) {
  23862. names = (names instanceof Array) ? names : [names];
  23863. for (var i in names) {
  23864. if (mesh.name === names[i]) {
  23865. hierarchyIds.push(mesh.id);
  23866. return true;
  23867. }
  23868. }
  23869. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  23870. hierarchyIds.push(mesh.id);
  23871. return true;
  23872. }
  23873. return false;
  23874. };
  23875. var logOperation = function (operation, producer) {
  23876. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  23877. };
  23878. BABYLON.SceneLoader.RegisterPlugin({
  23879. extensions: ".babylon",
  23880. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  23881. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23882. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23883. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23884. // and avoid problems with multiple concurrent .babylon loads.
  23885. var log = "importMesh has failed JSON parse";
  23886. try {
  23887. var parsedData = JSON.parse(data);
  23888. log = "";
  23889. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23890. var loadedSkeletonsIds = [];
  23891. var loadedMaterialsIds = [];
  23892. var hierarchyIds = [];
  23893. var index;
  23894. var cache;
  23895. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23896. var parsedMesh = parsedData.meshes[index];
  23897. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  23898. if (meshesNames instanceof Array) {
  23899. // Remove found mesh name from list.
  23900. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  23901. }
  23902. //Geometry?
  23903. if (parsedMesh.geometryId) {
  23904. //does the file contain geometries?
  23905. if (parsedData.geometries) {
  23906. //find the correct geometry and add it to the scene
  23907. var found = false;
  23908. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  23909. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  23910. return;
  23911. }
  23912. else {
  23913. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  23914. if (parsedGeometryData.id === parsedMesh.geometryId) {
  23915. switch (geometryType) {
  23916. case "boxes":
  23917. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  23918. break;
  23919. case "spheres":
  23920. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  23921. break;
  23922. case "cylinders":
  23923. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  23924. break;
  23925. case "toruses":
  23926. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  23927. break;
  23928. case "grounds":
  23929. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  23930. break;
  23931. case "planes":
  23932. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  23933. break;
  23934. case "torusKnots":
  23935. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  23936. break;
  23937. case "vertexData":
  23938. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  23939. break;
  23940. }
  23941. found = true;
  23942. }
  23943. });
  23944. }
  23945. });
  23946. if (!found) {
  23947. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  23948. }
  23949. }
  23950. }
  23951. // Material ?
  23952. if (parsedMesh.materialId) {
  23953. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  23954. if (!materialFound && parsedData.multiMaterials) {
  23955. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  23956. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  23957. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  23958. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  23959. var subMatId = parsedMultiMaterial.materials[matIndex];
  23960. loadedMaterialsIds.push(subMatId);
  23961. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  23962. log += "\n\tMaterial " + mat.toString(fullDetails);
  23963. }
  23964. loadedMaterialsIds.push(parsedMultiMaterial.id);
  23965. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23966. materialFound = true;
  23967. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  23968. break;
  23969. }
  23970. }
  23971. }
  23972. if (!materialFound) {
  23973. loadedMaterialsIds.push(parsedMesh.materialId);
  23974. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  23975. if (!mat) {
  23976. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  23977. }
  23978. else {
  23979. log += "\n\tMaterial " + mat.toString(fullDetails);
  23980. }
  23981. }
  23982. }
  23983. // Skeleton ?
  23984. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  23985. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  23986. if (!skeletonAlreadyLoaded) {
  23987. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  23988. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  23989. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  23990. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23991. skeletons.push(skeleton);
  23992. loadedSkeletonsIds.push(parsedSkeleton.id);
  23993. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  23994. }
  23995. }
  23996. }
  23997. }
  23998. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23999. meshes.push(mesh);
  24000. log += "\n\tMesh " + mesh.toString(fullDetails);
  24001. }
  24002. }
  24003. // Connecting parents
  24004. var currentMesh;
  24005. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24006. currentMesh = scene.meshes[index];
  24007. if (currentMesh._waitingParentId) {
  24008. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  24009. currentMesh._waitingParentId = undefined;
  24010. }
  24011. }
  24012. // freeze and compute world matrix application
  24013. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24014. currentMesh = scene.meshes[index];
  24015. if (currentMesh._waitingFreezeWorldMatrix) {
  24016. currentMesh.freezeWorldMatrix();
  24017. currentMesh._waitingFreezeWorldMatrix = undefined;
  24018. }
  24019. else {
  24020. currentMesh.computeWorldMatrix(true);
  24021. }
  24022. }
  24023. // Particles
  24024. if (parsedData.particleSystems) {
  24025. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24026. var parsedParticleSystem = parsedData.particleSystems[index];
  24027. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  24028. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  24029. }
  24030. }
  24031. }
  24032. return true;
  24033. }
  24034. catch (err) {
  24035. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  24036. log = null;
  24037. throw err;
  24038. }
  24039. finally {
  24040. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24041. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24042. }
  24043. }
  24044. },
  24045. load: function (scene, data, rootUrl) {
  24046. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24047. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24048. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24049. // and avoid problems with multiple concurrent .babylon loads.
  24050. var log = "importScene has failed JSON parse";
  24051. try {
  24052. var parsedData = JSON.parse(data);
  24053. log = "";
  24054. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24055. // Scene
  24056. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  24057. scene.autoClear = parsedData.autoClear;
  24058. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  24059. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  24060. if (parsedData.gravity) {
  24061. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  24062. }
  24063. // Fog
  24064. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  24065. scene.fogMode = parsedData.fogMode;
  24066. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  24067. scene.fogStart = parsedData.fogStart;
  24068. scene.fogEnd = parsedData.fogEnd;
  24069. scene.fogDensity = parsedData.fogDensity;
  24070. log += "\tFog mode for scene: ";
  24071. switch (scene.fogMode) {
  24072. // getters not compiling, so using hardcoded
  24073. case 1:
  24074. log += "exp\n";
  24075. break;
  24076. case 2:
  24077. log += "exp2\n";
  24078. break;
  24079. case 3:
  24080. log += "linear\n";
  24081. break;
  24082. }
  24083. }
  24084. //Physics
  24085. if (parsedData.physicsEnabled) {
  24086. var physicsPlugin;
  24087. if (parsedData.physicsEngine === "cannon") {
  24088. physicsPlugin = new BABYLON.CannonJSPlugin();
  24089. }
  24090. else if (parsedData.physicsEngine === "oimo") {
  24091. physicsPlugin = new BABYLON.OimoJSPlugin();
  24092. }
  24093. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  24094. //else - default engine, which is currently oimo
  24095. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  24096. scene.enablePhysics(physicsGravity, physicsPlugin);
  24097. }
  24098. //collisions, if defined. otherwise, default is true
  24099. if (parsedData.collisionsEnabled != undefined) {
  24100. scene.collisionsEnabled = parsedData.collisionsEnabled;
  24101. }
  24102. scene.workerCollisions = !!parsedData.workerCollisions;
  24103. var index;
  24104. var cache;
  24105. // Lights
  24106. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  24107. var parsedLight = parsedData.lights[index];
  24108. var light = BABYLON.Light.Parse(parsedLight, scene);
  24109. log += (index === 0 ? "\n\tLights:" : "");
  24110. log += "\n\t\t" + light.toString(fullDetails);
  24111. }
  24112. // Animations
  24113. if (parsedData.animations) {
  24114. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  24115. var parsedAnimation = parsedData.animations[index];
  24116. var animation = BABYLON.Animation.Parse(parsedAnimation);
  24117. scene.animations.push(animation);
  24118. log += (index === 0 ? "\n\tAnimations:" : "");
  24119. log += "\n\t\t" + animation.toString(fullDetails);
  24120. }
  24121. }
  24122. // Materials
  24123. if (parsedData.materials) {
  24124. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24125. var parsedMaterial = parsedData.materials[index];
  24126. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24127. log += (index === 0 ? "\n\tMaterials:" : "");
  24128. log += "\n\t\t" + mat.toString(fullDetails);
  24129. }
  24130. }
  24131. if (parsedData.multiMaterials) {
  24132. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  24133. var parsedMultiMaterial = parsedData.multiMaterials[index];
  24134. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24135. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  24136. log += "\n\t\t" + mmat.toString(fullDetails);
  24137. }
  24138. }
  24139. // Skeletons
  24140. if (parsedData.skeletons) {
  24141. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  24142. var parsedSkeleton = parsedData.skeletons[index];
  24143. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24144. log += (index === 0 ? "\n\tSkeletons:" : "");
  24145. log += "\n\t\t" + skeleton.toString(fullDetails);
  24146. }
  24147. }
  24148. // Geometries
  24149. var geometries = parsedData.geometries;
  24150. if (geometries) {
  24151. // Boxes
  24152. var boxes = geometries.boxes;
  24153. if (boxes) {
  24154. for (index = 0, cache = boxes.length; index < cache; index++) {
  24155. var parsedBox = boxes[index];
  24156. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  24157. }
  24158. }
  24159. // Spheres
  24160. var spheres = geometries.spheres;
  24161. if (spheres) {
  24162. for (index = 0, cache = spheres.length; index < cache; index++) {
  24163. var parsedSphere = spheres[index];
  24164. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  24165. }
  24166. }
  24167. // Cylinders
  24168. var cylinders = geometries.cylinders;
  24169. if (cylinders) {
  24170. for (index = 0, cache = cylinders.length; index < cache; index++) {
  24171. var parsedCylinder = cylinders[index];
  24172. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  24173. }
  24174. }
  24175. // Toruses
  24176. var toruses = geometries.toruses;
  24177. if (toruses) {
  24178. for (index = 0, cache = toruses.length; index < cache; index++) {
  24179. var parsedTorus = toruses[index];
  24180. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  24181. }
  24182. }
  24183. // Grounds
  24184. var grounds = geometries.grounds;
  24185. if (grounds) {
  24186. for (index = 0, cache = grounds.length; index < cache; index++) {
  24187. var parsedGround = grounds[index];
  24188. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  24189. }
  24190. }
  24191. // Planes
  24192. var planes = geometries.planes;
  24193. if (planes) {
  24194. for (index = 0, cache = planes.length; index < cache; index++) {
  24195. var parsedPlane = planes[index];
  24196. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  24197. }
  24198. }
  24199. // TorusKnots
  24200. var torusKnots = geometries.torusKnots;
  24201. if (torusKnots) {
  24202. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  24203. var parsedTorusKnot = torusKnots[index];
  24204. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  24205. }
  24206. }
  24207. // VertexData
  24208. var vertexData = geometries.vertexData;
  24209. if (vertexData) {
  24210. for (index = 0, cache = vertexData.length; index < cache; index++) {
  24211. var parsedVertexData = vertexData[index];
  24212. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  24213. }
  24214. }
  24215. }
  24216. // Meshes
  24217. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24218. var parsedMesh = parsedData.meshes[index];
  24219. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24220. log += (index === 0 ? "\n\tMeshes:" : "");
  24221. log += "\n\t\t" + mesh.toString(fullDetails);
  24222. }
  24223. // Cameras
  24224. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  24225. var parsedCamera = parsedData.cameras[index];
  24226. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  24227. log += (index === 0 ? "\n\tCameras:" : "");
  24228. log += "\n\t\t" + camera.toString(fullDetails);
  24229. }
  24230. if (parsedData.activeCameraID) {
  24231. scene.setActiveCameraByID(parsedData.activeCameraID);
  24232. }
  24233. // Browsing all the graph to connect the dots
  24234. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  24235. var camera = scene.cameras[index];
  24236. if (camera._waitingParentId) {
  24237. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  24238. camera._waitingParentId = undefined;
  24239. }
  24240. }
  24241. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  24242. var light = scene.lights[index];
  24243. if (light._waitingParentId) {
  24244. light.parent = scene.getLastEntryByID(light._waitingParentId);
  24245. light._waitingParentId = undefined;
  24246. }
  24247. }
  24248. // Sounds
  24249. var loadedSounds = [];
  24250. var loadedSound;
  24251. if (BABYLON.AudioEngine && parsedData.sounds) {
  24252. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  24253. var parsedSound = parsedData.sounds[index];
  24254. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  24255. if (!parsedSound.url)
  24256. parsedSound.url = parsedSound.name;
  24257. if (!loadedSounds[parsedSound.url]) {
  24258. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  24259. loadedSounds[parsedSound.url] = loadedSound;
  24260. }
  24261. else {
  24262. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  24263. }
  24264. }
  24265. else {
  24266. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24267. }
  24268. }
  24269. }
  24270. loadedSounds = [];
  24271. // Connect parents & children and parse actions
  24272. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24273. var mesh = scene.meshes[index];
  24274. if (mesh._waitingParentId) {
  24275. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24276. mesh._waitingParentId = undefined;
  24277. }
  24278. if (mesh._waitingActions) {
  24279. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24280. mesh._waitingActions = undefined;
  24281. }
  24282. }
  24283. // freeze world matrix application
  24284. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24285. var currentMesh = scene.meshes[index];
  24286. if (currentMesh._waitingFreezeWorldMatrix) {
  24287. currentMesh.freezeWorldMatrix();
  24288. currentMesh._waitingFreezeWorldMatrix = undefined;
  24289. }
  24290. else {
  24291. currentMesh.computeWorldMatrix(true);
  24292. }
  24293. }
  24294. // Particles Systems
  24295. if (parsedData.particleSystems) {
  24296. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24297. var parsedParticleSystem = parsedData.particleSystems[index];
  24298. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24299. }
  24300. }
  24301. // Lens flares
  24302. if (parsedData.lensFlareSystems) {
  24303. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24304. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24305. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24306. }
  24307. }
  24308. // Shadows
  24309. if (parsedData.shadowGenerators) {
  24310. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24311. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24312. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24313. }
  24314. }
  24315. // Actions (scene)
  24316. if (parsedData.actions) {
  24317. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24318. }
  24319. // Finish
  24320. return true;
  24321. }
  24322. catch (err) {
  24323. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24324. log = null;
  24325. throw err;
  24326. }
  24327. finally {
  24328. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24329. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24330. }
  24331. }
  24332. }
  24333. });
  24334. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24335. })(BABYLON || (BABYLON = {}));
  24336. var BABYLON;
  24337. (function (BABYLON) {
  24338. var SpriteManager = (function () {
  24339. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24340. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24341. this.name = name;
  24342. this.cellSize = cellSize;
  24343. this.sprites = new Array();
  24344. this.renderingGroupId = 0;
  24345. this.layerMask = 0x0FFFFFFF;
  24346. this.fogEnabled = true;
  24347. this.isPickable = false;
  24348. this._vertexDeclaration = [4, 4, 4, 4];
  24349. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24350. this._capacity = capacity;
  24351. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24352. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24353. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24354. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24355. this._scene = scene;
  24356. this._scene.spriteManagers.push(this);
  24357. // VBO
  24358. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24359. var indices = [];
  24360. var index = 0;
  24361. for (var count = 0; count < capacity; count++) {
  24362. indices.push(index);
  24363. indices.push(index + 1);
  24364. indices.push(index + 2);
  24365. indices.push(index);
  24366. indices.push(index + 2);
  24367. indices.push(index + 3);
  24368. index += 4;
  24369. }
  24370. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24371. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24372. // Effects
  24373. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24374. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24375. }
  24376. Object.defineProperty(SpriteManager.prototype, "texture", {
  24377. get: function () {
  24378. return this._spriteTexture;
  24379. },
  24380. set: function (value) {
  24381. this._spriteTexture = value;
  24382. },
  24383. enumerable: true,
  24384. configurable: true
  24385. });
  24386. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24387. var arrayOffset = index * 16;
  24388. if (offsetX === 0)
  24389. offsetX = this._epsilon;
  24390. else if (offsetX === 1)
  24391. offsetX = 1 - this._epsilon;
  24392. if (offsetY === 0)
  24393. offsetY = this._epsilon;
  24394. else if (offsetY === 1)
  24395. offsetY = 1 - this._epsilon;
  24396. this._vertices[arrayOffset] = sprite.position.x;
  24397. this._vertices[arrayOffset + 1] = sprite.position.y;
  24398. this._vertices[arrayOffset + 2] = sprite.position.z;
  24399. this._vertices[arrayOffset + 3] = sprite.angle;
  24400. this._vertices[arrayOffset + 4] = sprite.width;
  24401. this._vertices[arrayOffset + 5] = sprite.height;
  24402. this._vertices[arrayOffset + 6] = offsetX;
  24403. this._vertices[arrayOffset + 7] = offsetY;
  24404. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24405. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24406. var offset = (sprite.cellIndex / rowSize) >> 0;
  24407. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24408. this._vertices[arrayOffset + 11] = offset;
  24409. // Color
  24410. this._vertices[arrayOffset + 12] = sprite.color.r;
  24411. this._vertices[arrayOffset + 13] = sprite.color.g;
  24412. this._vertices[arrayOffset + 14] = sprite.color.b;
  24413. this._vertices[arrayOffset + 15] = sprite.color.a;
  24414. };
  24415. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24416. var count = Math.min(this._capacity, this.sprites.length);
  24417. var min = BABYLON.Vector3.Zero();
  24418. var max = BABYLON.Vector3.Zero();
  24419. var distance = Number.MAX_VALUE;
  24420. var currentSprite;
  24421. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24422. var cameraView = camera.getViewMatrix();
  24423. for (var index = 0; index < count; index++) {
  24424. var sprite = this.sprites[index];
  24425. if (!sprite) {
  24426. continue;
  24427. }
  24428. if (predicate) {
  24429. if (!predicate(sprite)) {
  24430. continue;
  24431. }
  24432. }
  24433. else if (!sprite.isPickable) {
  24434. continue;
  24435. }
  24436. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24437. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24438. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24439. if (ray.intersectsBoxMinMax(min, max)) {
  24440. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24441. if (distance > currentDistance) {
  24442. distance = currentDistance;
  24443. currentSprite = sprite;
  24444. if (fastCheck) {
  24445. break;
  24446. }
  24447. }
  24448. }
  24449. }
  24450. if (currentSprite) {
  24451. var result = new BABYLON.PickingInfo();
  24452. result.hit = true;
  24453. result.pickedSprite = currentSprite;
  24454. result.distance = distance;
  24455. return result;
  24456. }
  24457. return null;
  24458. };
  24459. SpriteManager.prototype.render = function () {
  24460. // Check
  24461. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24462. return;
  24463. var engine = this._scene.getEngine();
  24464. var baseSize = this._spriteTexture.getBaseSize();
  24465. // Sprites
  24466. var deltaTime = engine.getDeltaTime();
  24467. var max = Math.min(this._capacity, this.sprites.length);
  24468. var rowSize = baseSize.width / this.cellSize;
  24469. var offset = 0;
  24470. for (var index = 0; index < max; index++) {
  24471. var sprite = this.sprites[index];
  24472. if (!sprite) {
  24473. continue;
  24474. }
  24475. sprite._animate(deltaTime);
  24476. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24477. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24478. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24479. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24480. }
  24481. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24482. // Render
  24483. var effect = this._effectBase;
  24484. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24485. effect = this._effectFog;
  24486. }
  24487. engine.enableEffect(effect);
  24488. var viewMatrix = this._scene.getViewMatrix();
  24489. effect.setTexture("diffuseSampler", this._spriteTexture);
  24490. effect.setMatrix("view", viewMatrix);
  24491. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24492. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  24493. // Fog
  24494. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24495. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  24496. effect.setColor3("vFogColor", this._scene.fogColor);
  24497. }
  24498. // VBOs
  24499. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24500. // Draw order
  24501. engine.setDepthFunctionToLessOrEqual();
  24502. effect.setBool("alphaTest", true);
  24503. engine.setColorWrite(false);
  24504. engine.draw(true, 0, max * 6);
  24505. engine.setColorWrite(true);
  24506. effect.setBool("alphaTest", false);
  24507. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24508. engine.draw(true, 0, max * 6);
  24509. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24510. };
  24511. SpriteManager.prototype.dispose = function () {
  24512. if (this._vertexBuffer) {
  24513. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24514. this._vertexBuffer = null;
  24515. }
  24516. if (this._indexBuffer) {
  24517. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24518. this._indexBuffer = null;
  24519. }
  24520. if (this._spriteTexture) {
  24521. this._spriteTexture.dispose();
  24522. this._spriteTexture = null;
  24523. }
  24524. // Remove from scene
  24525. var index = this._scene.spriteManagers.indexOf(this);
  24526. this._scene.spriteManagers.splice(index, 1);
  24527. // Callback
  24528. if (this.onDispose) {
  24529. this.onDispose();
  24530. }
  24531. };
  24532. return SpriteManager;
  24533. })();
  24534. BABYLON.SpriteManager = SpriteManager;
  24535. })(BABYLON || (BABYLON = {}));
  24536. var BABYLON;
  24537. (function (BABYLON) {
  24538. var Sprite = (function () {
  24539. function Sprite(name, manager) {
  24540. this.name = name;
  24541. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24542. this.width = 1.0;
  24543. this.height = 1.0;
  24544. this.angle = 0;
  24545. this.cellIndex = 0;
  24546. this.invertU = 0;
  24547. this.invertV = 0;
  24548. this.animations = new Array();
  24549. this.isPickable = false;
  24550. this._animationStarted = false;
  24551. this._loopAnimation = false;
  24552. this._fromIndex = 0;
  24553. this._toIndex = 0;
  24554. this._delay = 0;
  24555. this._direction = 1;
  24556. this._frameCount = 0;
  24557. this._time = 0;
  24558. this._manager = manager;
  24559. this._manager.sprites.push(this);
  24560. this.position = BABYLON.Vector3.Zero();
  24561. }
  24562. Object.defineProperty(Sprite.prototype, "size", {
  24563. get: function () {
  24564. return this.width;
  24565. },
  24566. set: function (value) {
  24567. this.width = value;
  24568. this.height = value;
  24569. },
  24570. enumerable: true,
  24571. configurable: true
  24572. });
  24573. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  24574. this._fromIndex = from;
  24575. this._toIndex = to;
  24576. this._loopAnimation = loop;
  24577. this._delay = delay;
  24578. this._animationStarted = true;
  24579. this._direction = from < to ? 1 : -1;
  24580. this.cellIndex = from;
  24581. this._time = 0;
  24582. };
  24583. Sprite.prototype.stopAnimation = function () {
  24584. this._animationStarted = false;
  24585. };
  24586. Sprite.prototype._animate = function (deltaTime) {
  24587. if (!this._animationStarted)
  24588. return;
  24589. this._time += deltaTime;
  24590. if (this._time > this._delay) {
  24591. this._time = this._time % this._delay;
  24592. this.cellIndex += this._direction;
  24593. if (this.cellIndex == this._toIndex) {
  24594. if (this._loopAnimation) {
  24595. this.cellIndex = this._fromIndex;
  24596. }
  24597. else {
  24598. this._animationStarted = false;
  24599. if (this.disposeWhenFinishedAnimating) {
  24600. this.dispose();
  24601. }
  24602. }
  24603. }
  24604. }
  24605. };
  24606. Sprite.prototype.dispose = function () {
  24607. for (var i = 0; i < this._manager.sprites.length; i++) {
  24608. if (this._manager.sprites[i] == this) {
  24609. this._manager.sprites.splice(i, 1);
  24610. }
  24611. }
  24612. };
  24613. return Sprite;
  24614. })();
  24615. BABYLON.Sprite = Sprite;
  24616. })(BABYLON || (BABYLON = {}));
  24617. var BABYLON;
  24618. (function (BABYLON) {
  24619. var Layer = (function () {
  24620. function Layer(name, imgUrl, scene, isBackground, color) {
  24621. this.name = name;
  24622. this.scale = new BABYLON.Vector2(1, 1);
  24623. this.offset = new BABYLON.Vector2(0, 0);
  24624. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  24625. this._vertexDeclaration = [2];
  24626. this._vertexStrideSize = 2 * 4;
  24627. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  24628. this.isBackground = isBackground === undefined ? true : isBackground;
  24629. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  24630. this._scene = scene;
  24631. this._scene.layers.push(this);
  24632. // VBO
  24633. var vertices = [];
  24634. vertices.push(1, 1);
  24635. vertices.push(-1, 1);
  24636. vertices.push(-1, -1);
  24637. vertices.push(1, -1);
  24638. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  24639. // Indices
  24640. var indices = [];
  24641. indices.push(0);
  24642. indices.push(1);
  24643. indices.push(2);
  24644. indices.push(0);
  24645. indices.push(2);
  24646. indices.push(3);
  24647. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24648. // Effects
  24649. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  24650. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  24651. }
  24652. Layer.prototype.render = function () {
  24653. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  24654. // Check
  24655. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  24656. return;
  24657. var engine = this._scene.getEngine();
  24658. if (this.onBeforeRender) {
  24659. this.onBeforeRender();
  24660. }
  24661. // Render
  24662. engine.enableEffect(currentEffect);
  24663. engine.setState(false);
  24664. // Texture
  24665. currentEffect.setTexture("textureSampler", this.texture);
  24666. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  24667. // Color
  24668. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  24669. // Scale / offset
  24670. currentEffect.setVector2("offset", this.offset);
  24671. currentEffect.setVector2("scale", this.scale);
  24672. // VBOs
  24673. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  24674. // Draw order
  24675. if (!this._alphaTestEffect) {
  24676. engine.setAlphaMode(this.alphaBlendingMode);
  24677. engine.draw(true, 0, 6);
  24678. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24679. }
  24680. else {
  24681. engine.draw(true, 0, 6);
  24682. }
  24683. if (this.onAfterRender) {
  24684. this.onAfterRender();
  24685. }
  24686. };
  24687. Layer.prototype.dispose = function () {
  24688. if (this._vertexBuffer) {
  24689. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24690. this._vertexBuffer = null;
  24691. }
  24692. if (this._indexBuffer) {
  24693. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24694. this._indexBuffer = null;
  24695. }
  24696. if (this.texture) {
  24697. this.texture.dispose();
  24698. this.texture = null;
  24699. }
  24700. // Remove from scene
  24701. var index = this._scene.layers.indexOf(this);
  24702. this._scene.layers.splice(index, 1);
  24703. // Callback
  24704. if (this.onDispose) {
  24705. this.onDispose();
  24706. }
  24707. };
  24708. return Layer;
  24709. })();
  24710. BABYLON.Layer = Layer;
  24711. })(BABYLON || (BABYLON = {}));
  24712. var BABYLON;
  24713. (function (BABYLON) {
  24714. var Particle = (function () {
  24715. function Particle() {
  24716. this.position = BABYLON.Vector3.Zero();
  24717. this.direction = BABYLON.Vector3.Zero();
  24718. this.color = new BABYLON.Color4(0, 0, 0, 0);
  24719. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  24720. this.lifeTime = 1.0;
  24721. this.age = 0;
  24722. this.size = 0;
  24723. this.angle = 0;
  24724. this.angularSpeed = 0;
  24725. }
  24726. Particle.prototype.copyTo = function (other) {
  24727. other.position.copyFrom(this.position);
  24728. other.direction.copyFrom(this.direction);
  24729. other.color.copyFrom(this.color);
  24730. other.colorStep.copyFrom(this.colorStep);
  24731. other.lifeTime = this.lifeTime;
  24732. other.age = this.age;
  24733. other.size = this.size;
  24734. other.angle = this.angle;
  24735. other.angularSpeed = this.angularSpeed;
  24736. };
  24737. return Particle;
  24738. })();
  24739. BABYLON.Particle = Particle;
  24740. })(BABYLON || (BABYLON = {}));
  24741. var BABYLON;
  24742. (function (BABYLON) {
  24743. var randomNumber = function (min, max) {
  24744. if (min === max) {
  24745. return (min);
  24746. }
  24747. var random = Math.random();
  24748. return ((random * (max - min)) + min);
  24749. };
  24750. var ParticleSystem = (function () {
  24751. function ParticleSystem(name, capacity, scene, customEffect) {
  24752. var _this = this;
  24753. this.name = name;
  24754. // Members
  24755. this.animations = [];
  24756. this.renderingGroupId = 0;
  24757. this.emitter = null;
  24758. this.emitRate = 10;
  24759. this.manualEmitCount = -1;
  24760. this.updateSpeed = 0.01;
  24761. this.targetStopDuration = 0;
  24762. this.disposeOnStop = false;
  24763. this.minEmitPower = 1;
  24764. this.maxEmitPower = 1;
  24765. this.minLifeTime = 1;
  24766. this.maxLifeTime = 1;
  24767. this.minSize = 1;
  24768. this.maxSize = 1;
  24769. this.minAngularSpeed = 0;
  24770. this.maxAngularSpeed = 0;
  24771. this.layerMask = 0x0FFFFFFF;
  24772. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  24773. this.forceDepthWrite = false;
  24774. this.gravity = BABYLON.Vector3.Zero();
  24775. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  24776. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  24777. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  24778. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  24779. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24780. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24781. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  24782. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24783. this.particles = new Array();
  24784. this._vertexDeclaration = [3, 4, 4];
  24785. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  24786. this._stockParticles = new Array();
  24787. this._newPartsExcess = 0;
  24788. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  24789. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  24790. this._scaledDirection = BABYLON.Vector3.Zero();
  24791. this._scaledGravity = BABYLON.Vector3.Zero();
  24792. this._currentRenderId = -1;
  24793. this._started = false;
  24794. this._stopped = false;
  24795. this._actualFrame = 0;
  24796. this.id = name;
  24797. this._capacity = capacity;
  24798. this._scene = scene;
  24799. this._customEffect = customEffect;
  24800. scene.particleSystems.push(this);
  24801. // VBO
  24802. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24803. var indices = [];
  24804. var index = 0;
  24805. for (var count = 0; count < capacity; count++) {
  24806. indices.push(index);
  24807. indices.push(index + 1);
  24808. indices.push(index + 2);
  24809. indices.push(index);
  24810. indices.push(index + 2);
  24811. indices.push(index + 3);
  24812. index += 4;
  24813. }
  24814. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24815. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24816. // Default behaviors
  24817. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  24818. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  24819. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  24820. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  24821. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  24822. };
  24823. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  24824. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  24825. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  24826. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  24827. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  24828. };
  24829. this.updateFunction = function (particles) {
  24830. for (var index = 0; index < particles.length; index++) {
  24831. var particle = particles[index];
  24832. particle.age += _this._scaledUpdateSpeed;
  24833. if (particle.age >= particle.lifeTime) {
  24834. _this.recycleParticle(particle);
  24835. index--;
  24836. continue;
  24837. }
  24838. else {
  24839. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  24840. particle.color.addInPlace(_this._scaledColorStep);
  24841. if (particle.color.a < 0)
  24842. particle.color.a = 0;
  24843. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  24844. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  24845. particle.position.addInPlace(_this._scaledDirection);
  24846. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  24847. particle.direction.addInPlace(_this._scaledGravity);
  24848. }
  24849. }
  24850. };
  24851. }
  24852. ParticleSystem.prototype.recycleParticle = function (particle) {
  24853. var lastParticle = this.particles.pop();
  24854. if (lastParticle !== particle) {
  24855. lastParticle.copyTo(particle);
  24856. this._stockParticles.push(lastParticle);
  24857. }
  24858. };
  24859. ParticleSystem.prototype.getCapacity = function () {
  24860. return this._capacity;
  24861. };
  24862. ParticleSystem.prototype.isAlive = function () {
  24863. return this._alive;
  24864. };
  24865. ParticleSystem.prototype.isStarted = function () {
  24866. return this._started;
  24867. };
  24868. ParticleSystem.prototype.start = function () {
  24869. this._started = true;
  24870. this._stopped = false;
  24871. this._actualFrame = 0;
  24872. };
  24873. ParticleSystem.prototype.stop = function () {
  24874. this._stopped = true;
  24875. };
  24876. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  24877. var offset = index * 11;
  24878. this._vertices[offset] = particle.position.x;
  24879. this._vertices[offset + 1] = particle.position.y;
  24880. this._vertices[offset + 2] = particle.position.z;
  24881. this._vertices[offset + 3] = particle.color.r;
  24882. this._vertices[offset + 4] = particle.color.g;
  24883. this._vertices[offset + 5] = particle.color.b;
  24884. this._vertices[offset + 6] = particle.color.a;
  24885. this._vertices[offset + 7] = particle.angle;
  24886. this._vertices[offset + 8] = particle.size;
  24887. this._vertices[offset + 9] = offsetX;
  24888. this._vertices[offset + 10] = offsetY;
  24889. };
  24890. ParticleSystem.prototype._update = function (newParticles) {
  24891. // Update current
  24892. this._alive = this.particles.length > 0;
  24893. this.updateFunction(this.particles);
  24894. // Add new ones
  24895. var worldMatrix;
  24896. if (this.emitter.position) {
  24897. worldMatrix = this.emitter.getWorldMatrix();
  24898. }
  24899. else {
  24900. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  24901. }
  24902. var particle;
  24903. for (var index = 0; index < newParticles; index++) {
  24904. if (this.particles.length === this._capacity) {
  24905. break;
  24906. }
  24907. if (this._stockParticles.length !== 0) {
  24908. particle = this._stockParticles.pop();
  24909. particle.age = 0;
  24910. }
  24911. else {
  24912. particle = new BABYLON.Particle();
  24913. }
  24914. this.particles.push(particle);
  24915. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  24916. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  24917. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  24918. particle.size = randomNumber(this.minSize, this.maxSize);
  24919. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  24920. this.startPositionFunction(worldMatrix, particle.position, particle);
  24921. var step = randomNumber(0, 1.0);
  24922. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  24923. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  24924. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  24925. }
  24926. };
  24927. ParticleSystem.prototype._getEffect = function () {
  24928. if (this._customEffect) {
  24929. return this._customEffect;
  24930. }
  24931. ;
  24932. var defines = [];
  24933. if (this._scene.clipPlane) {
  24934. defines.push("#define CLIPPLANE");
  24935. }
  24936. // Effect
  24937. var join = defines.join("\n");
  24938. if (this._cachedDefines !== join) {
  24939. this._cachedDefines = join;
  24940. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  24941. }
  24942. return this._effect;
  24943. };
  24944. ParticleSystem.prototype.animate = function () {
  24945. if (!this._started)
  24946. return;
  24947. var effect = this._getEffect();
  24948. // Check
  24949. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  24950. return;
  24951. if (this._currentRenderId === this._scene.getRenderId()) {
  24952. return;
  24953. }
  24954. this._currentRenderId = this._scene.getRenderId();
  24955. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  24956. // determine the number of particles we need to create
  24957. var newParticles;
  24958. if (this.manualEmitCount > -1) {
  24959. newParticles = this.manualEmitCount;
  24960. this._newPartsExcess = 0;
  24961. this.manualEmitCount = 0;
  24962. }
  24963. else {
  24964. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  24965. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  24966. }
  24967. if (this._newPartsExcess > 1.0) {
  24968. newParticles += this._newPartsExcess >> 0;
  24969. this._newPartsExcess -= this._newPartsExcess >> 0;
  24970. }
  24971. this._alive = false;
  24972. if (!this._stopped) {
  24973. this._actualFrame += this._scaledUpdateSpeed;
  24974. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  24975. this.stop();
  24976. }
  24977. else {
  24978. newParticles = 0;
  24979. }
  24980. this._update(newParticles);
  24981. // Stopped?
  24982. if (this._stopped) {
  24983. if (!this._alive) {
  24984. this._started = false;
  24985. if (this.disposeOnStop) {
  24986. this._scene._toBeDisposed.push(this);
  24987. }
  24988. }
  24989. }
  24990. // Update VBO
  24991. var offset = 0;
  24992. for (var index = 0; index < this.particles.length; index++) {
  24993. var particle = this.particles[index];
  24994. this._appendParticleVertex(offset++, particle, 0, 0);
  24995. this._appendParticleVertex(offset++, particle, 1, 0);
  24996. this._appendParticleVertex(offset++, particle, 1, 1);
  24997. this._appendParticleVertex(offset++, particle, 0, 1);
  24998. }
  24999. var engine = this._scene.getEngine();
  25000. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  25001. };
  25002. ParticleSystem.prototype.render = function () {
  25003. var effect = this._getEffect();
  25004. // Check
  25005. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  25006. return 0;
  25007. var engine = this._scene.getEngine();
  25008. // Render
  25009. engine.enableEffect(effect);
  25010. engine.setState(false);
  25011. var viewMatrix = this._scene.getViewMatrix();
  25012. effect.setTexture("diffuseSampler", this.particleTexture);
  25013. effect.setMatrix("view", viewMatrix);
  25014. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25015. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  25016. if (this._scene.clipPlane) {
  25017. var clipPlane = this._scene.clipPlane;
  25018. var invView = viewMatrix.clone();
  25019. invView.invert();
  25020. effect.setMatrix("invView", invView);
  25021. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25022. }
  25023. // VBOs
  25024. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25025. // Draw order
  25026. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  25027. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  25028. }
  25029. else {
  25030. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25031. }
  25032. if (this.forceDepthWrite) {
  25033. engine.setDepthWrite(true);
  25034. }
  25035. engine.draw(true, 0, this.particles.length * 6);
  25036. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25037. return this.particles.length;
  25038. };
  25039. ParticleSystem.prototype.dispose = function () {
  25040. if (this._vertexBuffer) {
  25041. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25042. this._vertexBuffer = null;
  25043. }
  25044. if (this._indexBuffer) {
  25045. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25046. this._indexBuffer = null;
  25047. }
  25048. if (this.particleTexture) {
  25049. this.particleTexture.dispose();
  25050. this.particleTexture = null;
  25051. }
  25052. // Remove from scene
  25053. var index = this._scene.particleSystems.indexOf(this);
  25054. this._scene.particleSystems.splice(index, 1);
  25055. // Callback
  25056. if (this.onDispose) {
  25057. this.onDispose();
  25058. }
  25059. };
  25060. // Clone
  25061. ParticleSystem.prototype.clone = function (name, newEmitter) {
  25062. var result = new ParticleSystem(name, this._capacity, this._scene);
  25063. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  25064. if (newEmitter === undefined) {
  25065. newEmitter = this.emitter;
  25066. }
  25067. result.emitter = newEmitter;
  25068. if (this.particleTexture) {
  25069. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  25070. }
  25071. result.start();
  25072. return result;
  25073. };
  25074. ParticleSystem.prototype.serialize = function () {
  25075. var serializationObject = {};
  25076. serializationObject.name = this.name;
  25077. serializationObject.id = this.id;
  25078. // Emitter
  25079. if (this.emitter.position) {
  25080. serializationObject.emitterId = this.emitter.id;
  25081. }
  25082. else {
  25083. serializationObject.emitter = this.emitter.asArray();
  25084. }
  25085. serializationObject.capacity = this.getCapacity();
  25086. if (this.particleTexture) {
  25087. serializationObject.textureName = this.particleTexture.name;
  25088. }
  25089. // Animations
  25090. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25091. // Particle system
  25092. serializationObject.minAngularSpeed = this.minAngularSpeed;
  25093. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  25094. serializationObject.minSize = this.minSize;
  25095. serializationObject.maxSize = this.maxSize;
  25096. serializationObject.minEmitPower = this.minEmitPower;
  25097. serializationObject.maxEmitPower = this.maxEmitPower;
  25098. serializationObject.minLifeTime = this.minLifeTime;
  25099. serializationObject.maxLifeTime = this.maxLifeTime;
  25100. serializationObject.emitRate = this.emitRate;
  25101. serializationObject.minEmitBox = this.minEmitBox.asArray();
  25102. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  25103. serializationObject.gravity = this.gravity.asArray();
  25104. serializationObject.direction1 = this.direction1.asArray();
  25105. serializationObject.direction2 = this.direction2.asArray();
  25106. serializationObject.color1 = this.color1.asArray();
  25107. serializationObject.color2 = this.color2.asArray();
  25108. serializationObject.colorDead = this.colorDead.asArray();
  25109. serializationObject.updateSpeed = this.updateSpeed;
  25110. serializationObject.targetStopDuration = this.targetStopDuration;
  25111. serializationObject.textureMask = this.textureMask.asArray();
  25112. serializationObject.blendMode = this.blendMode;
  25113. return serializationObject;
  25114. };
  25115. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  25116. var name = parsedParticleSystem.name;
  25117. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  25118. if (parsedParticleSystem.id) {
  25119. particleSystem.id = parsedParticleSystem.id;
  25120. }
  25121. // Texture
  25122. if (parsedParticleSystem.textureName) {
  25123. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  25124. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  25125. }
  25126. // Emitter
  25127. if (parsedParticleSystem.emitterId) {
  25128. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  25129. }
  25130. else {
  25131. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  25132. }
  25133. // Animations
  25134. if (parsedParticleSystem.animations) {
  25135. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  25136. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  25137. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25138. }
  25139. }
  25140. if (parsedParticleSystem.autoAnimate) {
  25141. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  25142. }
  25143. // Particle system
  25144. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  25145. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  25146. particleSystem.minSize = parsedParticleSystem.minSize;
  25147. particleSystem.maxSize = parsedParticleSystem.maxSize;
  25148. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  25149. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  25150. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  25151. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  25152. particleSystem.emitRate = parsedParticleSystem.emitRate;
  25153. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  25154. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  25155. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  25156. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  25157. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  25158. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  25159. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  25160. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  25161. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  25162. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  25163. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  25164. particleSystem.blendMode = parsedParticleSystem.blendMode;
  25165. if (!parsedParticleSystem.preventAutoStart) {
  25166. particleSystem.start();
  25167. }
  25168. return particleSystem;
  25169. };
  25170. // Statics
  25171. ParticleSystem.BLENDMODE_ONEONE = 0;
  25172. ParticleSystem.BLENDMODE_STANDARD = 1;
  25173. return ParticleSystem;
  25174. })();
  25175. BABYLON.ParticleSystem = ParticleSystem;
  25176. })(BABYLON || (BABYLON = {}));
  25177. var BABYLON;
  25178. (function (BABYLON) {
  25179. var AnimationRange = (function () {
  25180. function AnimationRange(name, from, to) {
  25181. this.name = name;
  25182. this.from = from;
  25183. this.to = to;
  25184. }
  25185. AnimationRange.prototype.clone = function () {
  25186. return new AnimationRange(this.name, this.from, this.to);
  25187. };
  25188. return AnimationRange;
  25189. })();
  25190. BABYLON.AnimationRange = AnimationRange;
  25191. /**
  25192. * Composed of a frame, and an action function
  25193. */
  25194. var AnimationEvent = (function () {
  25195. function AnimationEvent(frame, action, onlyOnce) {
  25196. this.frame = frame;
  25197. this.action = action;
  25198. this.onlyOnce = onlyOnce;
  25199. this.isDone = false;
  25200. }
  25201. return AnimationEvent;
  25202. })();
  25203. BABYLON.AnimationEvent = AnimationEvent;
  25204. var PathCursor = (function () {
  25205. function PathCursor(path) {
  25206. this.path = path;
  25207. this._onchange = new Array();
  25208. this.value = 0;
  25209. this.animations = new Array();
  25210. }
  25211. PathCursor.prototype.getPoint = function () {
  25212. var point = this.path.getPointAtLengthPosition(this.value);
  25213. return new BABYLON.Vector3(point.x, 0, point.y);
  25214. };
  25215. PathCursor.prototype.moveAhead = function (step) {
  25216. if (step === void 0) { step = 0.002; }
  25217. this.move(step);
  25218. return this;
  25219. };
  25220. PathCursor.prototype.moveBack = function (step) {
  25221. if (step === void 0) { step = 0.002; }
  25222. this.move(-step);
  25223. return this;
  25224. };
  25225. PathCursor.prototype.move = function (step) {
  25226. if (Math.abs(step) > 1) {
  25227. throw "step size should be less than 1.";
  25228. }
  25229. this.value += step;
  25230. this.ensureLimits();
  25231. this.raiseOnChange();
  25232. return this;
  25233. };
  25234. PathCursor.prototype.ensureLimits = function () {
  25235. while (this.value > 1) {
  25236. this.value -= 1;
  25237. }
  25238. while (this.value < 0) {
  25239. this.value += 1;
  25240. }
  25241. return this;
  25242. };
  25243. // used by animation engine
  25244. PathCursor.prototype.markAsDirty = function (propertyName) {
  25245. this.ensureLimits();
  25246. this.raiseOnChange();
  25247. return this;
  25248. };
  25249. PathCursor.prototype.raiseOnChange = function () {
  25250. var _this = this;
  25251. this._onchange.forEach(function (f) { return f(_this); });
  25252. return this;
  25253. };
  25254. PathCursor.prototype.onchange = function (f) {
  25255. this._onchange.push(f);
  25256. return this;
  25257. };
  25258. return PathCursor;
  25259. })();
  25260. BABYLON.PathCursor = PathCursor;
  25261. var Animation = (function () {
  25262. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  25263. this.name = name;
  25264. this.targetProperty = targetProperty;
  25265. this.framePerSecond = framePerSecond;
  25266. this.dataType = dataType;
  25267. this.loopMode = loopMode;
  25268. this.enableBlending = enableBlending;
  25269. this._offsetsCache = {};
  25270. this._highLimitsCache = {};
  25271. this._stopped = false;
  25272. this._blendingFactor = 0;
  25273. // The set of event that will be linked to this animation
  25274. this._events = new Array();
  25275. this.allowMatricesInterpolation = false;
  25276. this.blendingSpeed = 0.01;
  25277. this._ranges = {};
  25278. this.targetPropertyPath = targetProperty.split(".");
  25279. this.dataType = dataType;
  25280. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  25281. }
  25282. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  25283. var dataType = undefined;
  25284. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  25285. dataType = Animation.ANIMATIONTYPE_FLOAT;
  25286. }
  25287. else if (from instanceof BABYLON.Quaternion) {
  25288. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  25289. }
  25290. else if (from instanceof BABYLON.Vector3) {
  25291. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25292. }
  25293. else if (from instanceof BABYLON.Vector2) {
  25294. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25295. }
  25296. else if (from instanceof BABYLON.Color3) {
  25297. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25298. }
  25299. if (dataType == undefined) {
  25300. return null;
  25301. }
  25302. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25303. var keys = [];
  25304. keys.push({ frame: 0, value: from });
  25305. keys.push({ frame: totalFrame, value: to });
  25306. animation.setKeys(keys);
  25307. if (easingFunction !== undefined) {
  25308. animation.setEasingFunction(easingFunction);
  25309. }
  25310. return animation;
  25311. };
  25312. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25313. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25314. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25315. };
  25316. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25317. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25318. node.animations.push(animation);
  25319. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25320. };
  25321. // Methods
  25322. /**
  25323. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25324. */
  25325. Animation.prototype.toString = function (fullDetails) {
  25326. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25327. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25328. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25329. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25330. if (fullDetails) {
  25331. ret += ", Ranges: {";
  25332. var first = true;
  25333. for (var name in this._ranges) {
  25334. if (!first) {
  25335. ret + ", ";
  25336. first = false;
  25337. }
  25338. ret += name;
  25339. }
  25340. ret += "}";
  25341. }
  25342. return ret;
  25343. };
  25344. /**
  25345. * Add an event to this animation.
  25346. */
  25347. Animation.prototype.addEvent = function (event) {
  25348. this._events.push(event);
  25349. };
  25350. /**
  25351. * Remove all events found at the given frame
  25352. * @param frame
  25353. */
  25354. Animation.prototype.removeEvents = function (frame) {
  25355. for (var index = 0; index < this._events.length; index++) {
  25356. if (this._events[index].frame === frame) {
  25357. this._events.splice(index, 1);
  25358. index--;
  25359. }
  25360. }
  25361. };
  25362. Animation.prototype.createRange = function (name, from, to) {
  25363. // check name not already in use; could happen for bones after serialized
  25364. if (!this._ranges[name]) {
  25365. this._ranges[name] = new AnimationRange(name, from, to);
  25366. }
  25367. };
  25368. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25369. if (deleteFrames === void 0) { deleteFrames = true; }
  25370. if (this._ranges[name]) {
  25371. if (deleteFrames) {
  25372. var from = this._ranges[name].from;
  25373. var to = this._ranges[name].to;
  25374. // this loop MUST go high to low for multiple splices to work
  25375. for (var key = this._keys.length - 1; key >= 0; key--) {
  25376. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25377. this._keys.splice(key, 1);
  25378. }
  25379. }
  25380. }
  25381. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25382. }
  25383. };
  25384. Animation.prototype.getRange = function (name) {
  25385. return this._ranges[name];
  25386. };
  25387. Animation.prototype.reset = function () {
  25388. this._offsetsCache = {};
  25389. this._highLimitsCache = {};
  25390. this.currentFrame = 0;
  25391. this._blendingFactor = 0;
  25392. this._originalBlendValue = null;
  25393. };
  25394. Animation.prototype.isStopped = function () {
  25395. return this._stopped;
  25396. };
  25397. Animation.prototype.getKeys = function () {
  25398. return this._keys;
  25399. };
  25400. Animation.prototype.getHighestFrame = function () {
  25401. var ret = 0;
  25402. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25403. if (ret < this._keys[key].frame) {
  25404. ret = this._keys[key].frame;
  25405. }
  25406. }
  25407. return ret;
  25408. };
  25409. Animation.prototype.getEasingFunction = function () {
  25410. return this._easingFunction;
  25411. };
  25412. Animation.prototype.setEasingFunction = function (easingFunction) {
  25413. this._easingFunction = easingFunction;
  25414. };
  25415. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25416. return startValue + (endValue - startValue) * gradient;
  25417. };
  25418. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25419. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25420. };
  25421. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25422. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  25423. };
  25424. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  25425. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  25426. };
  25427. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  25428. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  25429. };
  25430. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  25431. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  25432. };
  25433. Animation.prototype.clone = function () {
  25434. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  25435. if (this._keys) {
  25436. clone.setKeys(this._keys);
  25437. }
  25438. if (this._ranges) {
  25439. clone._ranges = {};
  25440. for (var name in this._ranges) {
  25441. clone._ranges[name] = this._ranges[name].clone();
  25442. }
  25443. }
  25444. return clone;
  25445. };
  25446. Animation.prototype.setKeys = function (values) {
  25447. this._keys = values.slice(0);
  25448. this._offsetsCache = {};
  25449. this._highLimitsCache = {};
  25450. };
  25451. Animation.prototype._getKeyValue = function (value) {
  25452. if (typeof value === "function") {
  25453. return value();
  25454. }
  25455. return value;
  25456. };
  25457. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  25458. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  25459. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  25460. }
  25461. this.currentFrame = currentFrame;
  25462. // Try to get a hash to find the right key
  25463. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  25464. if (this._keys[startKey].frame >= currentFrame) {
  25465. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  25466. startKey--;
  25467. }
  25468. }
  25469. for (var key = startKey; key < this._keys.length; key++) {
  25470. if (this._keys[key + 1].frame >= currentFrame) {
  25471. var startValue = this._getKeyValue(this._keys[key].value);
  25472. var endValue = this._getKeyValue(this._keys[key + 1].value);
  25473. // gradient : percent of currentFrame between the frame inf and the frame sup
  25474. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  25475. // check for easingFunction and correction of gradient
  25476. if (this._easingFunction != null) {
  25477. gradient = this._easingFunction.ease(gradient);
  25478. }
  25479. switch (this.dataType) {
  25480. // Float
  25481. case Animation.ANIMATIONTYPE_FLOAT:
  25482. switch (loopMode) {
  25483. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25484. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25485. return this.floatInterpolateFunction(startValue, endValue, gradient);
  25486. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25487. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  25488. }
  25489. break;
  25490. // Quaternion
  25491. case Animation.ANIMATIONTYPE_QUATERNION:
  25492. var quaternion = null;
  25493. switch (loopMode) {
  25494. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25495. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25496. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  25497. break;
  25498. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25499. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25500. break;
  25501. }
  25502. return quaternion;
  25503. // Vector3
  25504. case Animation.ANIMATIONTYPE_VECTOR3:
  25505. switch (loopMode) {
  25506. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25507. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25508. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  25509. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25510. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25511. }
  25512. // Vector2
  25513. case Animation.ANIMATIONTYPE_VECTOR2:
  25514. switch (loopMode) {
  25515. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25516. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25517. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  25518. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25519. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25520. }
  25521. // Color3
  25522. case Animation.ANIMATIONTYPE_COLOR3:
  25523. switch (loopMode) {
  25524. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25525. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25526. return this.color3InterpolateFunction(startValue, endValue, gradient);
  25527. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25528. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25529. }
  25530. // Matrix
  25531. case Animation.ANIMATIONTYPE_MATRIX:
  25532. switch (loopMode) {
  25533. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25534. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25535. if (this.allowMatricesInterpolation) {
  25536. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  25537. }
  25538. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25539. return startValue;
  25540. }
  25541. default:
  25542. break;
  25543. }
  25544. break;
  25545. }
  25546. }
  25547. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  25548. };
  25549. Animation.prototype.setValue = function (currentValue, blend) {
  25550. if (blend === void 0) { blend = false; }
  25551. // Set value
  25552. var path;
  25553. var destination;
  25554. if (this.targetPropertyPath.length > 1) {
  25555. var property = this._target[this.targetPropertyPath[0]];
  25556. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  25557. property = property[this.targetPropertyPath[index]];
  25558. }
  25559. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  25560. destination = property;
  25561. }
  25562. else {
  25563. path = this.targetPropertyPath[0];
  25564. destination = this._target;
  25565. }
  25566. // Blending
  25567. if (this.enableBlending && this._blendingFactor <= 1.0) {
  25568. if (!this._originalBlendValue) {
  25569. this._originalBlendValue = destination[path];
  25570. }
  25571. if (this._originalBlendValue.prototype) {
  25572. if (this._originalBlendValue.prototype.Lerp) {
  25573. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25574. }
  25575. else {
  25576. destination[path] = currentValue;
  25577. }
  25578. }
  25579. else {
  25580. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  25581. }
  25582. this._blendingFactor += this.blendingSpeed;
  25583. }
  25584. else {
  25585. destination[path] = currentValue;
  25586. }
  25587. if (this._target.markAsDirty) {
  25588. this._target.markAsDirty(this.targetProperty);
  25589. }
  25590. };
  25591. Animation.prototype.goToFrame = function (frame) {
  25592. if (frame < this._keys[0].frame) {
  25593. frame = this._keys[0].frame;
  25594. }
  25595. else if (frame > this._keys[this._keys.length - 1].frame) {
  25596. frame = this._keys[this._keys.length - 1].frame;
  25597. }
  25598. var currentValue = this._interpolate(frame, 0, this.loopMode);
  25599. this.setValue(currentValue);
  25600. };
  25601. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  25602. if (blend === void 0) { blend = false; }
  25603. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  25604. this._stopped = true;
  25605. return false;
  25606. }
  25607. var returnValue = true;
  25608. // Adding a start key at frame 0 if missing
  25609. if (this._keys[0].frame !== 0) {
  25610. var newKey = { frame: 0, value: this._keys[0].value };
  25611. this._keys.splice(0, 0, newKey);
  25612. }
  25613. // Check limits
  25614. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  25615. from = this._keys[0].frame;
  25616. }
  25617. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  25618. to = this._keys[this._keys.length - 1].frame;
  25619. }
  25620. // Compute ratio
  25621. var range = to - from;
  25622. var offsetValue;
  25623. // ratio represents the frame delta between from and to
  25624. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  25625. var highLimitValue = 0;
  25626. if (ratio > range && !loop) {
  25627. returnValue = false;
  25628. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  25629. }
  25630. else {
  25631. // Get max value if required
  25632. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  25633. var keyOffset = to.toString() + from.toString();
  25634. if (!this._offsetsCache[keyOffset]) {
  25635. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25636. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25637. switch (this.dataType) {
  25638. // Float
  25639. case Animation.ANIMATIONTYPE_FLOAT:
  25640. this._offsetsCache[keyOffset] = toValue - fromValue;
  25641. break;
  25642. // Quaternion
  25643. case Animation.ANIMATIONTYPE_QUATERNION:
  25644. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25645. break;
  25646. // Vector3
  25647. case Animation.ANIMATIONTYPE_VECTOR3:
  25648. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25649. // Vector2
  25650. case Animation.ANIMATIONTYPE_VECTOR2:
  25651. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25652. // Color3
  25653. case Animation.ANIMATIONTYPE_COLOR3:
  25654. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25655. default:
  25656. break;
  25657. }
  25658. this._highLimitsCache[keyOffset] = toValue;
  25659. }
  25660. highLimitValue = this._highLimitsCache[keyOffset];
  25661. offsetValue = this._offsetsCache[keyOffset];
  25662. }
  25663. }
  25664. if (offsetValue === undefined) {
  25665. switch (this.dataType) {
  25666. // Float
  25667. case Animation.ANIMATIONTYPE_FLOAT:
  25668. offsetValue = 0;
  25669. break;
  25670. // Quaternion
  25671. case Animation.ANIMATIONTYPE_QUATERNION:
  25672. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  25673. break;
  25674. // Vector3
  25675. case Animation.ANIMATIONTYPE_VECTOR3:
  25676. offsetValue = BABYLON.Vector3.Zero();
  25677. break;
  25678. // Vector2
  25679. case Animation.ANIMATIONTYPE_VECTOR2:
  25680. offsetValue = BABYLON.Vector2.Zero();
  25681. break;
  25682. // Color3
  25683. case Animation.ANIMATIONTYPE_COLOR3:
  25684. offsetValue = BABYLON.Color3.Black();
  25685. }
  25686. }
  25687. // Compute value
  25688. var repeatCount = (ratio / range) >> 0;
  25689. var currentFrame = returnValue ? from + ratio % range : to;
  25690. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  25691. // Set value
  25692. this.setValue(currentValue);
  25693. // Check events
  25694. for (var index = 0; index < this._events.length; index++) {
  25695. if (currentFrame >= this._events[index].frame) {
  25696. var event = this._events[index];
  25697. if (!event.isDone) {
  25698. // If event should be done only once, remove it.
  25699. if (event.onlyOnce) {
  25700. this._events.splice(index, 1);
  25701. index--;
  25702. }
  25703. event.isDone = true;
  25704. event.action();
  25705. } // Don't do anything if the event has already be done.
  25706. }
  25707. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  25708. // reset event, the animation is looping
  25709. this._events[index].isDone = false;
  25710. }
  25711. }
  25712. if (!returnValue) {
  25713. this._stopped = true;
  25714. }
  25715. return returnValue;
  25716. };
  25717. Animation.prototype.serialize = function () {
  25718. var serializationObject = {};
  25719. serializationObject.name = this.name;
  25720. serializationObject.property = this.targetProperty;
  25721. serializationObject.framePerSecond = this.framePerSecond;
  25722. serializationObject.dataType = this.dataType;
  25723. serializationObject.loopBehavior = this.loopMode;
  25724. var dataType = this.dataType;
  25725. serializationObject.keys = [];
  25726. var keys = this.getKeys();
  25727. for (var index = 0; index < keys.length; index++) {
  25728. var animationKey = keys[index];
  25729. var key = {};
  25730. key.frame = animationKey.frame;
  25731. switch (dataType) {
  25732. case Animation.ANIMATIONTYPE_FLOAT:
  25733. key.values = [animationKey.value];
  25734. break;
  25735. case Animation.ANIMATIONTYPE_QUATERNION:
  25736. case Animation.ANIMATIONTYPE_MATRIX:
  25737. case Animation.ANIMATIONTYPE_VECTOR3:
  25738. case Animation.ANIMATIONTYPE_COLOR3:
  25739. key.values = animationKey.value.asArray();
  25740. break;
  25741. }
  25742. serializationObject.keys.push(key);
  25743. }
  25744. serializationObject.ranges = [];
  25745. for (var name in this._ranges) {
  25746. var range = {};
  25747. range.name = name;
  25748. range.from = this._ranges[name].from;
  25749. range.to = this._ranges[name].to;
  25750. serializationObject.ranges.push(range);
  25751. }
  25752. return serializationObject;
  25753. };
  25754. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  25755. get: function () {
  25756. return Animation._ANIMATIONTYPE_FLOAT;
  25757. },
  25758. enumerable: true,
  25759. configurable: true
  25760. });
  25761. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  25762. get: function () {
  25763. return Animation._ANIMATIONTYPE_VECTOR3;
  25764. },
  25765. enumerable: true,
  25766. configurable: true
  25767. });
  25768. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  25769. get: function () {
  25770. return Animation._ANIMATIONTYPE_VECTOR2;
  25771. },
  25772. enumerable: true,
  25773. configurable: true
  25774. });
  25775. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  25776. get: function () {
  25777. return Animation._ANIMATIONTYPE_QUATERNION;
  25778. },
  25779. enumerable: true,
  25780. configurable: true
  25781. });
  25782. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  25783. get: function () {
  25784. return Animation._ANIMATIONTYPE_MATRIX;
  25785. },
  25786. enumerable: true,
  25787. configurable: true
  25788. });
  25789. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  25790. get: function () {
  25791. return Animation._ANIMATIONTYPE_COLOR3;
  25792. },
  25793. enumerable: true,
  25794. configurable: true
  25795. });
  25796. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  25797. get: function () {
  25798. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  25799. },
  25800. enumerable: true,
  25801. configurable: true
  25802. });
  25803. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  25804. get: function () {
  25805. return Animation._ANIMATIONLOOPMODE_CYCLE;
  25806. },
  25807. enumerable: true,
  25808. configurable: true
  25809. });
  25810. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  25811. get: function () {
  25812. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  25813. },
  25814. enumerable: true,
  25815. configurable: true
  25816. });
  25817. Animation.Parse = function (parsedAnimation) {
  25818. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  25819. var dataType = parsedAnimation.dataType;
  25820. var keys = [];
  25821. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  25822. var key = parsedAnimation.keys[index];
  25823. var data;
  25824. switch (dataType) {
  25825. case Animation.ANIMATIONTYPE_FLOAT:
  25826. data = key.values[0];
  25827. break;
  25828. case Animation.ANIMATIONTYPE_QUATERNION:
  25829. data = BABYLON.Quaternion.FromArray(key.values);
  25830. break;
  25831. case Animation.ANIMATIONTYPE_MATRIX:
  25832. data = BABYLON.Matrix.FromArray(key.values);
  25833. break;
  25834. case Animation.ANIMATIONTYPE_COLOR3:
  25835. data = BABYLON.Color3.FromArray(key.values);
  25836. break;
  25837. case Animation.ANIMATIONTYPE_VECTOR3:
  25838. default:
  25839. data = BABYLON.Vector3.FromArray(key.values);
  25840. break;
  25841. }
  25842. keys.push({
  25843. frame: key.frame,
  25844. value: data
  25845. });
  25846. }
  25847. animation.setKeys(keys);
  25848. if (parsedAnimation.ranges) {
  25849. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  25850. data = parsedAnimation.ranges[index];
  25851. animation.createRange(data.name, data.from, data.to);
  25852. }
  25853. }
  25854. return animation;
  25855. };
  25856. Animation.AppendSerializedAnimations = function (source, destination) {
  25857. if (source.animations) {
  25858. destination.animations = [];
  25859. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  25860. var animation = source.animations[animationIndex];
  25861. destination.animations.push(animation.serialize());
  25862. }
  25863. }
  25864. };
  25865. // Statics
  25866. Animation._ANIMATIONTYPE_FLOAT = 0;
  25867. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  25868. Animation._ANIMATIONTYPE_QUATERNION = 2;
  25869. Animation._ANIMATIONTYPE_MATRIX = 3;
  25870. Animation._ANIMATIONTYPE_COLOR3 = 4;
  25871. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  25872. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  25873. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  25874. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  25875. return Animation;
  25876. })();
  25877. BABYLON.Animation = Animation;
  25878. })(BABYLON || (BABYLON = {}));
  25879. var BABYLON;
  25880. (function (BABYLON) {
  25881. var Animatable = (function () {
  25882. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  25883. if (fromFrame === void 0) { fromFrame = 0; }
  25884. if (toFrame === void 0) { toFrame = 100; }
  25885. if (loopAnimation === void 0) { loopAnimation = false; }
  25886. if (speedRatio === void 0) { speedRatio = 1.0; }
  25887. this.target = target;
  25888. this.fromFrame = fromFrame;
  25889. this.toFrame = toFrame;
  25890. this.loopAnimation = loopAnimation;
  25891. this.speedRatio = speedRatio;
  25892. this.onAnimationEnd = onAnimationEnd;
  25893. this._animations = new Array();
  25894. this._paused = false;
  25895. this.animationStarted = false;
  25896. if (animations) {
  25897. this.appendAnimations(target, animations);
  25898. }
  25899. this._scene = scene;
  25900. scene._activeAnimatables.push(this);
  25901. }
  25902. // Methods
  25903. Animatable.prototype.getAnimations = function () {
  25904. return this._animations;
  25905. };
  25906. Animatable.prototype.appendAnimations = function (target, animations) {
  25907. for (var index = 0; index < animations.length; index++) {
  25908. var animation = animations[index];
  25909. animation._target = target;
  25910. this._animations.push(animation);
  25911. }
  25912. };
  25913. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  25914. var animations = this._animations;
  25915. for (var index = 0; index < animations.length; index++) {
  25916. if (animations[index].targetProperty === property) {
  25917. return animations[index];
  25918. }
  25919. }
  25920. return null;
  25921. };
  25922. Animatable.prototype.reset = function () {
  25923. var animations = this._animations;
  25924. for (var index = 0; index < animations.length; index++) {
  25925. animations[index].reset();
  25926. }
  25927. this._localDelayOffset = null;
  25928. this._pausedDelay = null;
  25929. };
  25930. Animatable.prototype.enableBlending = function (blendingSpeed) {
  25931. var animations = this._animations;
  25932. for (var index = 0; index < animations.length; index++) {
  25933. animations[index].enableBlending = true;
  25934. animations[index].blendingSpeed = blendingSpeed;
  25935. }
  25936. };
  25937. Animatable.prototype.disableBlending = function () {
  25938. var animations = this._animations;
  25939. for (var index = 0; index < animations.length; index++) {
  25940. animations[index].enableBlending = false;
  25941. }
  25942. };
  25943. Animatable.prototype.goToFrame = function (frame) {
  25944. var animations = this._animations;
  25945. for (var index = 0; index < animations.length; index++) {
  25946. animations[index].goToFrame(frame);
  25947. }
  25948. };
  25949. Animatable.prototype.pause = function () {
  25950. if (this._paused) {
  25951. return;
  25952. }
  25953. this._paused = true;
  25954. };
  25955. Animatable.prototype.restart = function () {
  25956. this._paused = false;
  25957. };
  25958. Animatable.prototype.stop = function () {
  25959. var index = this._scene._activeAnimatables.indexOf(this);
  25960. if (index > -1) {
  25961. this._scene._activeAnimatables.splice(index, 1);
  25962. var animations = this._animations;
  25963. for (var index = 0; index < animations.length; index++) {
  25964. animations[index].reset();
  25965. }
  25966. if (this.onAnimationEnd) {
  25967. this.onAnimationEnd();
  25968. }
  25969. }
  25970. };
  25971. Animatable.prototype._animate = function (delay) {
  25972. if (this._paused) {
  25973. this.animationStarted = false;
  25974. if (!this._pausedDelay) {
  25975. this._pausedDelay = delay;
  25976. }
  25977. return true;
  25978. }
  25979. if (!this._localDelayOffset) {
  25980. this._localDelayOffset = delay;
  25981. }
  25982. else if (this._pausedDelay) {
  25983. this._localDelayOffset += delay - this._pausedDelay;
  25984. this._pausedDelay = null;
  25985. }
  25986. // Animating
  25987. var running = false;
  25988. var animations = this._animations;
  25989. var index;
  25990. for (index = 0; index < animations.length; index++) {
  25991. var animation = animations[index];
  25992. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  25993. running = running || isRunning;
  25994. }
  25995. this.animationStarted = running;
  25996. if (!running) {
  25997. // Remove from active animatables
  25998. index = this._scene._activeAnimatables.indexOf(this);
  25999. this._scene._activeAnimatables.splice(index, 1);
  26000. }
  26001. if (!running && this.onAnimationEnd) {
  26002. this.onAnimationEnd();
  26003. this.onAnimationEnd = null;
  26004. }
  26005. return running;
  26006. };
  26007. return Animatable;
  26008. })();
  26009. BABYLON.Animatable = Animatable;
  26010. })(BABYLON || (BABYLON = {}));
  26011. var BABYLON;
  26012. (function (BABYLON) {
  26013. var EasingFunction = (function () {
  26014. function EasingFunction() {
  26015. // Properties
  26016. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  26017. }
  26018. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  26019. get: function () {
  26020. return EasingFunction._EASINGMODE_EASEIN;
  26021. },
  26022. enumerable: true,
  26023. configurable: true
  26024. });
  26025. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  26026. get: function () {
  26027. return EasingFunction._EASINGMODE_EASEOUT;
  26028. },
  26029. enumerable: true,
  26030. configurable: true
  26031. });
  26032. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  26033. get: function () {
  26034. return EasingFunction._EASINGMODE_EASEINOUT;
  26035. },
  26036. enumerable: true,
  26037. configurable: true
  26038. });
  26039. EasingFunction.prototype.setEasingMode = function (easingMode) {
  26040. var n = Math.min(Math.max(easingMode, 0), 2);
  26041. this._easingMode = n;
  26042. };
  26043. EasingFunction.prototype.getEasingMode = function () {
  26044. return this._easingMode;
  26045. };
  26046. EasingFunction.prototype.easeInCore = function (gradient) {
  26047. throw new Error('You must implement this method');
  26048. };
  26049. EasingFunction.prototype.ease = function (gradient) {
  26050. switch (this._easingMode) {
  26051. case EasingFunction.EASINGMODE_EASEIN:
  26052. return this.easeInCore(gradient);
  26053. case EasingFunction.EASINGMODE_EASEOUT:
  26054. return (1 - this.easeInCore(1 - gradient));
  26055. }
  26056. if (gradient >= 0.5) {
  26057. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  26058. }
  26059. return (this.easeInCore(gradient * 2) * 0.5);
  26060. };
  26061. //Statics
  26062. EasingFunction._EASINGMODE_EASEIN = 0;
  26063. EasingFunction._EASINGMODE_EASEOUT = 1;
  26064. EasingFunction._EASINGMODE_EASEINOUT = 2;
  26065. return EasingFunction;
  26066. })();
  26067. BABYLON.EasingFunction = EasingFunction;
  26068. var CircleEase = (function (_super) {
  26069. __extends(CircleEase, _super);
  26070. function CircleEase() {
  26071. _super.apply(this, arguments);
  26072. }
  26073. CircleEase.prototype.easeInCore = function (gradient) {
  26074. gradient = Math.max(0, Math.min(1, gradient));
  26075. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  26076. };
  26077. return CircleEase;
  26078. })(EasingFunction);
  26079. BABYLON.CircleEase = CircleEase;
  26080. var BackEase = (function (_super) {
  26081. __extends(BackEase, _super);
  26082. function BackEase(amplitude) {
  26083. if (amplitude === void 0) { amplitude = 1; }
  26084. _super.call(this);
  26085. this.amplitude = amplitude;
  26086. }
  26087. BackEase.prototype.easeInCore = function (gradient) {
  26088. var num = Math.max(0, this.amplitude);
  26089. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  26090. };
  26091. return BackEase;
  26092. })(EasingFunction);
  26093. BABYLON.BackEase = BackEase;
  26094. var BounceEase = (function (_super) {
  26095. __extends(BounceEase, _super);
  26096. function BounceEase(bounces, bounciness) {
  26097. if (bounces === void 0) { bounces = 3; }
  26098. if (bounciness === void 0) { bounciness = 2; }
  26099. _super.call(this);
  26100. this.bounces = bounces;
  26101. this.bounciness = bounciness;
  26102. }
  26103. BounceEase.prototype.easeInCore = function (gradient) {
  26104. var y = Math.max(0.0, this.bounces);
  26105. var bounciness = this.bounciness;
  26106. if (bounciness <= 1.0) {
  26107. bounciness = 1.001;
  26108. }
  26109. var num9 = Math.pow(bounciness, y);
  26110. var num5 = 1.0 - bounciness;
  26111. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  26112. var num15 = gradient * num4;
  26113. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  26114. var num3 = Math.floor(num65);
  26115. var num13 = num3 + 1.0;
  26116. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  26117. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  26118. var num7 = (num8 + num12) * 0.5;
  26119. var num6 = gradient - num7;
  26120. var num2 = num7 - num8;
  26121. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  26122. };
  26123. return BounceEase;
  26124. })(EasingFunction);
  26125. BABYLON.BounceEase = BounceEase;
  26126. var CubicEase = (function (_super) {
  26127. __extends(CubicEase, _super);
  26128. function CubicEase() {
  26129. _super.apply(this, arguments);
  26130. }
  26131. CubicEase.prototype.easeInCore = function (gradient) {
  26132. return (gradient * gradient * gradient);
  26133. };
  26134. return CubicEase;
  26135. })(EasingFunction);
  26136. BABYLON.CubicEase = CubicEase;
  26137. var ElasticEase = (function (_super) {
  26138. __extends(ElasticEase, _super);
  26139. function ElasticEase(oscillations, springiness) {
  26140. if (oscillations === void 0) { oscillations = 3; }
  26141. if (springiness === void 0) { springiness = 3; }
  26142. _super.call(this);
  26143. this.oscillations = oscillations;
  26144. this.springiness = springiness;
  26145. }
  26146. ElasticEase.prototype.easeInCore = function (gradient) {
  26147. var num2;
  26148. var num3 = Math.max(0.0, this.oscillations);
  26149. var num = Math.max(0.0, this.springiness);
  26150. if (num == 0) {
  26151. num2 = gradient;
  26152. }
  26153. else {
  26154. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  26155. }
  26156. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  26157. };
  26158. return ElasticEase;
  26159. })(EasingFunction);
  26160. BABYLON.ElasticEase = ElasticEase;
  26161. var ExponentialEase = (function (_super) {
  26162. __extends(ExponentialEase, _super);
  26163. function ExponentialEase(exponent) {
  26164. if (exponent === void 0) { exponent = 2; }
  26165. _super.call(this);
  26166. this.exponent = exponent;
  26167. }
  26168. ExponentialEase.prototype.easeInCore = function (gradient) {
  26169. if (this.exponent <= 0) {
  26170. return gradient;
  26171. }
  26172. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  26173. };
  26174. return ExponentialEase;
  26175. })(EasingFunction);
  26176. BABYLON.ExponentialEase = ExponentialEase;
  26177. var PowerEase = (function (_super) {
  26178. __extends(PowerEase, _super);
  26179. function PowerEase(power) {
  26180. if (power === void 0) { power = 2; }
  26181. _super.call(this);
  26182. this.power = power;
  26183. }
  26184. PowerEase.prototype.easeInCore = function (gradient) {
  26185. var y = Math.max(0.0, this.power);
  26186. return Math.pow(gradient, y);
  26187. };
  26188. return PowerEase;
  26189. })(EasingFunction);
  26190. BABYLON.PowerEase = PowerEase;
  26191. var QuadraticEase = (function (_super) {
  26192. __extends(QuadraticEase, _super);
  26193. function QuadraticEase() {
  26194. _super.apply(this, arguments);
  26195. }
  26196. QuadraticEase.prototype.easeInCore = function (gradient) {
  26197. return (gradient * gradient);
  26198. };
  26199. return QuadraticEase;
  26200. })(EasingFunction);
  26201. BABYLON.QuadraticEase = QuadraticEase;
  26202. var QuarticEase = (function (_super) {
  26203. __extends(QuarticEase, _super);
  26204. function QuarticEase() {
  26205. _super.apply(this, arguments);
  26206. }
  26207. QuarticEase.prototype.easeInCore = function (gradient) {
  26208. return (gradient * gradient * gradient * gradient);
  26209. };
  26210. return QuarticEase;
  26211. })(EasingFunction);
  26212. BABYLON.QuarticEase = QuarticEase;
  26213. var QuinticEase = (function (_super) {
  26214. __extends(QuinticEase, _super);
  26215. function QuinticEase() {
  26216. _super.apply(this, arguments);
  26217. }
  26218. QuinticEase.prototype.easeInCore = function (gradient) {
  26219. return (gradient * gradient * gradient * gradient * gradient);
  26220. };
  26221. return QuinticEase;
  26222. })(EasingFunction);
  26223. BABYLON.QuinticEase = QuinticEase;
  26224. var SineEase = (function (_super) {
  26225. __extends(SineEase, _super);
  26226. function SineEase() {
  26227. _super.apply(this, arguments);
  26228. }
  26229. SineEase.prototype.easeInCore = function (gradient) {
  26230. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  26231. };
  26232. return SineEase;
  26233. })(EasingFunction);
  26234. BABYLON.SineEase = SineEase;
  26235. var BezierCurveEase = (function (_super) {
  26236. __extends(BezierCurveEase, _super);
  26237. function BezierCurveEase(x1, y1, x2, y2) {
  26238. if (x1 === void 0) { x1 = 0; }
  26239. if (y1 === void 0) { y1 = 0; }
  26240. if (x2 === void 0) { x2 = 1; }
  26241. if (y2 === void 0) { y2 = 1; }
  26242. _super.call(this);
  26243. this.x1 = x1;
  26244. this.y1 = y1;
  26245. this.x2 = x2;
  26246. this.y2 = y2;
  26247. }
  26248. BezierCurveEase.prototype.easeInCore = function (gradient) {
  26249. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  26250. };
  26251. return BezierCurveEase;
  26252. })(EasingFunction);
  26253. BABYLON.BezierCurveEase = BezierCurveEase;
  26254. })(BABYLON || (BABYLON = {}));
  26255. var BABYLON;
  26256. (function (BABYLON) {
  26257. var Bone = (function (_super) {
  26258. __extends(Bone, _super);
  26259. function Bone(name, skeleton, parentBone, matrix, restPose) {
  26260. _super.call(this, name, skeleton.getScene());
  26261. this.name = name;
  26262. this.children = new Array();
  26263. this.animations = new Array();
  26264. this._worldTransform = new BABYLON.Matrix();
  26265. this._absoluteTransform = new BABYLON.Matrix();
  26266. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  26267. this._skeleton = skeleton;
  26268. this._matrix = matrix;
  26269. this._baseMatrix = matrix;
  26270. this._restPose = restPose ? restPose : matrix.clone();
  26271. skeleton.bones.push(this);
  26272. if (parentBone) {
  26273. this._parent = parentBone;
  26274. parentBone.children.push(this);
  26275. }
  26276. else {
  26277. this._parent = null;
  26278. }
  26279. this._updateDifferenceMatrix();
  26280. }
  26281. // Members
  26282. Bone.prototype.getParent = function () {
  26283. return this._parent;
  26284. };
  26285. Bone.prototype.getLocalMatrix = function () {
  26286. return this._matrix;
  26287. };
  26288. Bone.prototype.getBaseMatrix = function () {
  26289. return this._baseMatrix;
  26290. };
  26291. Bone.prototype.getRestPose = function () {
  26292. return this._restPose;
  26293. };
  26294. Bone.prototype.returnToRest = function () {
  26295. this.updateMatrix(this._restPose.clone());
  26296. };
  26297. Bone.prototype.getWorldMatrix = function () {
  26298. return this._worldTransform;
  26299. };
  26300. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26301. return this._invertedAbsoluteTransform;
  26302. };
  26303. Bone.prototype.getAbsoluteTransform = function () {
  26304. return this._absoluteTransform;
  26305. };
  26306. // Methods
  26307. Bone.prototype.updateMatrix = function (matrix) {
  26308. this._baseMatrix = matrix.clone();
  26309. this._matrix = matrix.clone();
  26310. this._skeleton._markAsDirty();
  26311. this._updateDifferenceMatrix();
  26312. };
  26313. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26314. if (!rootMatrix) {
  26315. rootMatrix = this._baseMatrix;
  26316. }
  26317. if (this._parent) {
  26318. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26319. }
  26320. else {
  26321. this._absoluteTransform.copyFrom(rootMatrix);
  26322. }
  26323. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26324. for (var index = 0; index < this.children.length; index++) {
  26325. this.children[index]._updateDifferenceMatrix();
  26326. }
  26327. };
  26328. Bone.prototype.markAsDirty = function () {
  26329. this._currentRenderId++;
  26330. this._skeleton._markAsDirty();
  26331. };
  26332. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26333. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26334. // all animation may be coming from a library skeleton, so may need to create animation
  26335. if (this.animations.length === 0) {
  26336. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26337. this.animations[0].setKeys([]);
  26338. }
  26339. // get animation info / verify there is such a range from the source bone
  26340. var sourceRange = source.animations[0].getRange(rangeName);
  26341. if (!sourceRange) {
  26342. return false;
  26343. }
  26344. var from = sourceRange.from;
  26345. var to = sourceRange.to;
  26346. var sourceKeys = source.animations[0].getKeys();
  26347. // rescaling prep
  26348. var sourceBoneLength = source.length;
  26349. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26350. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26351. var destKeys = this.animations[0].getKeys();
  26352. // loop vars declaration / initialization
  26353. var orig;
  26354. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26355. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26356. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26357. var mat;
  26358. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26359. orig = sourceKeys[key];
  26360. if (orig.frame >= from && orig.frame <= to) {
  26361. if (scalingReqd) {
  26362. orig.value.decompose(origScale, origRotation, origTranslation);
  26363. origTranslation.scaleInPlace(ratio);
  26364. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26365. }
  26366. else {
  26367. mat = orig.value;
  26368. }
  26369. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26370. }
  26371. }
  26372. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26373. return true;
  26374. };
  26375. return Bone;
  26376. })(BABYLON.Node);
  26377. BABYLON.Bone = Bone;
  26378. })(BABYLON || (BABYLON = {}));
  26379. var BABYLON;
  26380. (function (BABYLON) {
  26381. var Skeleton = (function () {
  26382. function Skeleton(name, id, scene) {
  26383. this.name = name;
  26384. this.id = id;
  26385. this.bones = new Array();
  26386. this.needInitialSkinMatrix = false;
  26387. this._isDirty = true;
  26388. this._meshesWithPoseMatrix = new Array();
  26389. this._identity = BABYLON.Matrix.Identity();
  26390. this._ranges = {};
  26391. this.bones = [];
  26392. this._scene = scene;
  26393. scene.skeletons.push(this);
  26394. //make sure it will recalculate the matrix next time prepare is called.
  26395. this._isDirty = true;
  26396. }
  26397. // Members
  26398. Skeleton.prototype.getTransformMatrices = function (mesh) {
  26399. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  26400. return mesh._bonesTransformMatrices;
  26401. }
  26402. return this._transformMatrices;
  26403. };
  26404. Skeleton.prototype.getScene = function () {
  26405. return this._scene;
  26406. };
  26407. // Methods
  26408. /**
  26409. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26410. */
  26411. Skeleton.prototype.toString = function (fullDetails) {
  26412. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  26413. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26414. if (fullDetails) {
  26415. ret += ", Ranges: {";
  26416. var first = true;
  26417. for (var name in this._ranges) {
  26418. if (!first) {
  26419. ret + ", ";
  26420. first = false;
  26421. }
  26422. ret += name;
  26423. }
  26424. ret += "}";
  26425. }
  26426. return ret;
  26427. };
  26428. /**
  26429. * Get bone's index searching by name
  26430. * @param {string} name is bone's name to search for
  26431. * @return {number} Indice of the bone. Returns -1 if not found
  26432. */
  26433. Skeleton.prototype.getBoneIndexByName = function (name) {
  26434. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  26435. if (this.bones[boneIndex].name === name) {
  26436. return boneIndex;
  26437. }
  26438. }
  26439. return -1;
  26440. };
  26441. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  26442. // check name not already in use
  26443. if (!this._ranges[name]) {
  26444. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  26445. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26446. if (this.bones[i].animations[0]) {
  26447. this.bones[i].animations[0].createRange(name, from, to);
  26448. }
  26449. }
  26450. }
  26451. };
  26452. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  26453. if (deleteFrames === void 0) { deleteFrames = true; }
  26454. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26455. if (this.bones[i].animations[0]) {
  26456. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  26457. }
  26458. }
  26459. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26460. };
  26461. Skeleton.prototype.getAnimationRange = function (name) {
  26462. return this._ranges[name];
  26463. };
  26464. /**
  26465. * Returns as an Array, all AnimationRanges defined on this skeleton
  26466. */
  26467. Skeleton.prototype.getAnimationRanges = function () {
  26468. var animationRanges = [];
  26469. var name;
  26470. var i = 0;
  26471. for (name in this._ranges) {
  26472. animationRanges[i] = this._ranges[name];
  26473. i++;
  26474. }
  26475. return animationRanges;
  26476. };
  26477. /**
  26478. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  26479. */
  26480. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  26481. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26482. if (this._ranges[name] || !source.getAnimationRange(name)) {
  26483. return false;
  26484. }
  26485. var ret = true;
  26486. var frameOffset = this._getHighestAnimationFrame() + 1;
  26487. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  26488. var boneDict = {};
  26489. var sourceBones = source.bones;
  26490. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  26491. boneDict[sourceBones[i].name] = sourceBones[i];
  26492. }
  26493. if (this.bones.length !== sourceBones.length) {
  26494. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  26495. ret = false;
  26496. }
  26497. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26498. var boneName = this.bones[i].name;
  26499. var sourceBone = boneDict[boneName];
  26500. if (sourceBone) {
  26501. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  26502. }
  26503. else {
  26504. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  26505. ret = false;
  26506. }
  26507. }
  26508. // do not call createAnimationRange(), since it also is done to bones, which was already done
  26509. var range = source.getAnimationRange(name);
  26510. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  26511. return ret;
  26512. };
  26513. Skeleton.prototype.returnToRest = function () {
  26514. for (var index = 0; index < this.bones.length; index++) {
  26515. this.bones[index].returnToRest();
  26516. }
  26517. };
  26518. Skeleton.prototype._getHighestAnimationFrame = function () {
  26519. var ret = 0;
  26520. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26521. if (this.bones[i].animations[0]) {
  26522. var highest = this.bones[i].animations[0].getHighestFrame();
  26523. if (ret < highest) {
  26524. ret = highest;
  26525. }
  26526. }
  26527. }
  26528. return ret;
  26529. };
  26530. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  26531. var range = this.getAnimationRange(name);
  26532. if (!range) {
  26533. return null;
  26534. }
  26535. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  26536. };
  26537. Skeleton.prototype._markAsDirty = function () {
  26538. this._isDirty = true;
  26539. };
  26540. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  26541. this._meshesWithPoseMatrix.push(mesh);
  26542. };
  26543. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  26544. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  26545. if (index > -1) {
  26546. this._meshesWithPoseMatrix.splice(index, 1);
  26547. }
  26548. };
  26549. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  26550. for (var index = 0; index < this.bones.length; index++) {
  26551. var bone = this.bones[index];
  26552. var parentBone = bone.getParent();
  26553. if (parentBone) {
  26554. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  26555. }
  26556. else {
  26557. if (initialSkinMatrix) {
  26558. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  26559. }
  26560. else {
  26561. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  26562. }
  26563. }
  26564. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  26565. }
  26566. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  26567. };
  26568. Skeleton.prototype.prepare = function () {
  26569. if (!this._isDirty) {
  26570. return;
  26571. }
  26572. if (this.needInitialSkinMatrix) {
  26573. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  26574. var mesh = this._meshesWithPoseMatrix[index];
  26575. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  26576. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26577. }
  26578. var poseMatrix = mesh.getPoseMatrix();
  26579. // Prepare bones
  26580. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  26581. var bone = this.bones[boneIndex];
  26582. if (!bone.getParent()) {
  26583. var matrix = bone.getBaseMatrix();
  26584. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  26585. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  26586. }
  26587. }
  26588. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  26589. }
  26590. }
  26591. else {
  26592. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  26593. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26594. }
  26595. this._computeTransformMatrices(this._transformMatrices, null);
  26596. }
  26597. this._isDirty = false;
  26598. this._scene._activeBones += this.bones.length;
  26599. };
  26600. Skeleton.prototype.getAnimatables = function () {
  26601. if (!this._animatables || this._animatables.length !== this.bones.length) {
  26602. this._animatables = [];
  26603. for (var index = 0; index < this.bones.length; index++) {
  26604. this._animatables.push(this.bones[index]);
  26605. }
  26606. }
  26607. return this._animatables;
  26608. };
  26609. Skeleton.prototype.clone = function (name, id) {
  26610. var result = new Skeleton(name, id || name, this._scene);
  26611. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26612. for (var index = 0; index < this.bones.length; index++) {
  26613. var source = this.bones[index];
  26614. var parentBone = null;
  26615. if (source.getParent()) {
  26616. var parentIndex = this.bones.indexOf(source.getParent());
  26617. parentBone = result.bones[parentIndex];
  26618. }
  26619. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  26620. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  26621. }
  26622. if (this._ranges) {
  26623. result._ranges = {};
  26624. for (var rangeName in this._ranges) {
  26625. result._ranges[rangeName] = this._ranges[rangeName].clone();
  26626. }
  26627. }
  26628. this._isDirty = true;
  26629. return result;
  26630. };
  26631. Skeleton.prototype.dispose = function () {
  26632. this._meshesWithPoseMatrix = [];
  26633. // Animations
  26634. this.getScene().stopAnimation(this);
  26635. // Remove from scene
  26636. this.getScene().removeSkeleton(this);
  26637. };
  26638. Skeleton.prototype.serialize = function () {
  26639. var serializationObject = {};
  26640. serializationObject.name = this.name;
  26641. serializationObject.id = this.id;
  26642. serializationObject.bones = [];
  26643. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26644. for (var index = 0; index < this.bones.length; index++) {
  26645. var bone = this.bones[index];
  26646. var serializedBone = {
  26647. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  26648. name: bone.name,
  26649. matrix: bone.getLocalMatrix().toArray(),
  26650. rest: bone.getRestPose().toArray()
  26651. };
  26652. serializationObject.bones.push(serializedBone);
  26653. if (bone.length) {
  26654. serializedBone.length = bone.length;
  26655. }
  26656. if (bone.animations && bone.animations.length > 0) {
  26657. serializedBone.animation = bone.animations[0].serialize();
  26658. }
  26659. serializationObject.ranges = [];
  26660. for (var name in this._ranges) {
  26661. var range = {};
  26662. range.name = name;
  26663. range.from = this._ranges[name].from;
  26664. range.to = this._ranges[name].to;
  26665. serializationObject.ranges.push(range);
  26666. }
  26667. }
  26668. return serializationObject;
  26669. };
  26670. Skeleton.Parse = function (parsedSkeleton, scene) {
  26671. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  26672. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  26673. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  26674. var parsedBone = parsedSkeleton.bones[index];
  26675. var parentBone = null;
  26676. if (parsedBone.parentBoneIndex > -1) {
  26677. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  26678. }
  26679. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  26680. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  26681. if (parsedBone.length) {
  26682. bone.length = parsedBone.length;
  26683. }
  26684. if (parsedBone.animation) {
  26685. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  26686. }
  26687. }
  26688. // placed after bones, so createAnimationRange can cascade down
  26689. if (parsedSkeleton.ranges) {
  26690. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  26691. var data = parsedSkeleton.ranges[index];
  26692. skeleton.createAnimationRange(data.name, data.from, data.to);
  26693. }
  26694. }
  26695. return skeleton;
  26696. };
  26697. return Skeleton;
  26698. })();
  26699. BABYLON.Skeleton = Skeleton;
  26700. })(BABYLON || (BABYLON = {}));
  26701. var BABYLON;
  26702. (function (BABYLON) {
  26703. var PostProcess = (function () {
  26704. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  26705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  26706. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26707. this.name = name;
  26708. this.width = -1;
  26709. this.height = -1;
  26710. /*
  26711. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  26712. Can only be used on a single postprocess or on the last one of a chain.
  26713. */
  26714. this.enablePixelPerfectMode = false;
  26715. this._reusable = false;
  26716. this._textures = new BABYLON.SmartArray(2);
  26717. this._currentRenderTextureInd = 0;
  26718. this._scaleRatio = new BABYLON.Vector2(1, 1);
  26719. if (camera != null) {
  26720. this._camera = camera;
  26721. this._scene = camera.getScene();
  26722. camera.attachPostProcess(this);
  26723. this._engine = this._scene.getEngine();
  26724. }
  26725. else {
  26726. this._engine = engine;
  26727. }
  26728. this._renderRatio = ratio;
  26729. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  26730. this._reusable = reusable || false;
  26731. this._textureType = textureType;
  26732. this._samplers = samplers || [];
  26733. this._samplers.push("textureSampler");
  26734. this._fragmentUrl = fragmentUrl;
  26735. this._parameters = parameters || [];
  26736. this._parameters.push("scale");
  26737. this.updateEffect(defines);
  26738. }
  26739. PostProcess.prototype.updateEffect = function (defines) {
  26740. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  26741. };
  26742. PostProcess.prototype.isReusable = function () {
  26743. return this._reusable;
  26744. };
  26745. PostProcess.prototype.activate = function (camera, sourceTexture) {
  26746. camera = camera || this._camera;
  26747. var scene = camera.getScene();
  26748. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  26749. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  26750. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  26751. var desiredWidth = this._renderRatio.width || requiredWidth;
  26752. var desiredHeight = this._renderRatio.height || requiredHeight;
  26753. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  26754. if (!this._renderRatio.width) {
  26755. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  26756. }
  26757. if (!this._renderRatio.height) {
  26758. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  26759. }
  26760. }
  26761. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  26762. if (this._textures.length > 0) {
  26763. for (var i = 0; i < this._textures.length; i++) {
  26764. this._engine._releaseTexture(this._textures.data[i]);
  26765. }
  26766. this._textures.reset();
  26767. }
  26768. this.width = desiredWidth;
  26769. this.height = desiredHeight;
  26770. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  26771. if (this._reusable) {
  26772. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode, type: this._textureType }));
  26773. }
  26774. if (this.onSizeChanged) {
  26775. this.onSizeChanged();
  26776. }
  26777. }
  26778. if (this.enablePixelPerfectMode) {
  26779. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  26780. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  26781. }
  26782. else {
  26783. this._scaleRatio.copyFromFloats(1, 1);
  26784. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  26785. }
  26786. if (this.onActivate) {
  26787. this.onActivate(camera);
  26788. }
  26789. // Clear
  26790. if (this.clearColor) {
  26791. this._engine.clear(this.clearColor, true, true);
  26792. }
  26793. else {
  26794. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  26795. }
  26796. if (this._reusable) {
  26797. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  26798. }
  26799. };
  26800. Object.defineProperty(PostProcess.prototype, "isSupported", {
  26801. get: function () {
  26802. return this._effect.isSupported;
  26803. },
  26804. enumerable: true,
  26805. configurable: true
  26806. });
  26807. PostProcess.prototype.apply = function () {
  26808. // Check
  26809. if (!this._effect.isReady())
  26810. return null;
  26811. // States
  26812. this._engine.enableEffect(this._effect);
  26813. this._engine.setState(false);
  26814. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26815. this._engine.setDepthBuffer(false);
  26816. this._engine.setDepthWrite(false);
  26817. // Texture
  26818. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  26819. // Parameters
  26820. this._effect.setVector2("scale", this._scaleRatio);
  26821. if (this.onApply) {
  26822. this.onApply(this._effect);
  26823. }
  26824. return this._effect;
  26825. };
  26826. PostProcess.prototype.dispose = function (camera) {
  26827. camera = camera || this._camera;
  26828. if (this._textures.length > 0) {
  26829. for (var i = 0; i < this._textures.length; i++) {
  26830. this._engine._releaseTexture(this._textures.data[i]);
  26831. }
  26832. this._textures.reset();
  26833. }
  26834. if (!camera) {
  26835. return;
  26836. }
  26837. camera.detachPostProcess(this);
  26838. var index = camera._postProcesses.indexOf(this);
  26839. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  26840. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  26841. }
  26842. };
  26843. return PostProcess;
  26844. })();
  26845. BABYLON.PostProcess = PostProcess;
  26846. })(BABYLON || (BABYLON = {}));
  26847. var BABYLON;
  26848. (function (BABYLON) {
  26849. var PostProcessManager = (function () {
  26850. function PostProcessManager(scene) {
  26851. this._vertexDeclaration = [2];
  26852. this._vertexStrideSize = 2 * 4;
  26853. this._scene = scene;
  26854. }
  26855. PostProcessManager.prototype._prepareBuffers = function () {
  26856. if (this._vertexBuffer) {
  26857. return;
  26858. }
  26859. // VBO
  26860. var vertices = [];
  26861. vertices.push(1, 1);
  26862. vertices.push(-1, 1);
  26863. vertices.push(-1, -1);
  26864. vertices.push(1, -1);
  26865. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  26866. // Indices
  26867. var indices = [];
  26868. indices.push(0);
  26869. indices.push(1);
  26870. indices.push(2);
  26871. indices.push(0);
  26872. indices.push(2);
  26873. indices.push(3);
  26874. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26875. };
  26876. // Methods
  26877. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26878. var postProcesses = this._scene.activeCamera._postProcesses;
  26879. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26880. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26881. return false;
  26882. }
  26883. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  26884. return true;
  26885. };
  26886. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26887. var engine = this._scene.getEngine();
  26888. for (var index = 0; index < postProcesses.length; index++) {
  26889. if (index < postProcesses.length - 1) {
  26890. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26891. }
  26892. else {
  26893. if (targetTexture) {
  26894. engine.bindFramebuffer(targetTexture);
  26895. }
  26896. else {
  26897. engine.restoreDefaultFramebuffer();
  26898. }
  26899. }
  26900. var pp = postProcesses[index];
  26901. var effect = pp.apply();
  26902. if (effect) {
  26903. if (pp.onBeforeRender) {
  26904. pp.onBeforeRender(effect);
  26905. }
  26906. // VBOs
  26907. this._prepareBuffers();
  26908. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26909. // Draw order
  26910. engine.draw(true, 0, 6);
  26911. if (pp.onAfterRender) {
  26912. pp.onAfterRender(effect);
  26913. }
  26914. }
  26915. }
  26916. // Restore depth buffer
  26917. engine.setDepthBuffer(true);
  26918. engine.setDepthWrite(true);
  26919. };
  26920. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26921. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26922. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26923. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26924. return;
  26925. }
  26926. var engine = this._scene.getEngine();
  26927. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  26928. if (index < postProcessesTakenIndices.length - 1) {
  26929. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  26930. }
  26931. else {
  26932. if (targetTexture) {
  26933. engine.bindFramebuffer(targetTexture, faceIndex);
  26934. }
  26935. else {
  26936. engine.restoreDefaultFramebuffer();
  26937. }
  26938. }
  26939. if (doNotPresent) {
  26940. break;
  26941. }
  26942. var pp = postProcesses[postProcessesTakenIndices[index]];
  26943. var effect = pp.apply();
  26944. if (effect) {
  26945. if (pp.onBeforeRender) {
  26946. pp.onBeforeRender(effect);
  26947. }
  26948. // VBOs
  26949. this._prepareBuffers();
  26950. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26951. // Draw order
  26952. engine.draw(true, 0, 6);
  26953. if (pp.onAfterRender) {
  26954. pp.onAfterRender(effect);
  26955. }
  26956. }
  26957. }
  26958. // Restore depth buffer
  26959. engine.setDepthBuffer(true);
  26960. engine.setDepthWrite(true);
  26961. };
  26962. PostProcessManager.prototype.dispose = function () {
  26963. if (this._vertexBuffer) {
  26964. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  26965. this._vertexBuffer = null;
  26966. }
  26967. if (this._indexBuffer) {
  26968. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26969. this._indexBuffer = null;
  26970. }
  26971. };
  26972. return PostProcessManager;
  26973. })();
  26974. BABYLON.PostProcessManager = PostProcessManager;
  26975. })(BABYLON || (BABYLON = {}));
  26976. var BABYLON;
  26977. (function (BABYLON) {
  26978. var PassPostProcess = (function (_super) {
  26979. __extends(PassPostProcess, _super);
  26980. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26981. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  26982. }
  26983. return PassPostProcess;
  26984. })(BABYLON.PostProcess);
  26985. BABYLON.PassPostProcess = PassPostProcess;
  26986. })(BABYLON || (BABYLON = {}));
  26987. var BABYLON;
  26988. (function (BABYLON) {
  26989. /**
  26990. * This is a holder class for the physics joint created by the physics plugin.
  26991. * It holds a set of functions to control the underlying joint.
  26992. */
  26993. var PhysicsJoint = (function () {
  26994. function PhysicsJoint(type, jointData) {
  26995. this.type = type;
  26996. this.jointData = jointData;
  26997. jointData.nativeParams = jointData.nativeParams || {};
  26998. }
  26999. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  27000. get: function () {
  27001. return this._physicsJoint;
  27002. },
  27003. set: function (newJoint) {
  27004. if (this._physicsJoint) {
  27005. }
  27006. this._physicsJoint = newJoint;
  27007. },
  27008. enumerable: true,
  27009. configurable: true
  27010. });
  27011. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  27012. set: function (physicsPlugin) {
  27013. this._physicsPlugin = physicsPlugin;
  27014. },
  27015. enumerable: true,
  27016. configurable: true
  27017. });
  27018. /**
  27019. * Execute a function that is physics-plugin specific.
  27020. * @param {Function} func the function that will be executed.
  27021. * It accepts two parameters: the physics world and the physics joint.
  27022. */
  27023. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  27024. func(this._physicsPlugin.world, this._physicsJoint);
  27025. };
  27026. //TODO check if the native joints are the same
  27027. //Joint Types
  27028. PhysicsJoint.DistanceJoint = 0;
  27029. PhysicsJoint.HingeJoint = 1;
  27030. PhysicsJoint.BallAndSocketJoint = 2;
  27031. PhysicsJoint.WheelJoint = 3;
  27032. PhysicsJoint.SliderJoint = 4;
  27033. //OIMO
  27034. PhysicsJoint.PrismaticJoint = 5;
  27035. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  27036. PhysicsJoint.UniversalJoint = 6;
  27037. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  27038. //Cannon
  27039. //Similar to a Ball-Joint. Different in params
  27040. PhysicsJoint.PointToPointJoint = 8;
  27041. //Cannon only at the moment
  27042. PhysicsJoint.SpringJoint = 9;
  27043. return PhysicsJoint;
  27044. })();
  27045. BABYLON.PhysicsJoint = PhysicsJoint;
  27046. /**
  27047. * A class representing a physics distance joint.
  27048. */
  27049. var DistanceJoint = (function (_super) {
  27050. __extends(DistanceJoint, _super);
  27051. function DistanceJoint(jointData) {
  27052. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  27053. }
  27054. /**
  27055. * Update the predefined distance.
  27056. */
  27057. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  27058. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  27059. };
  27060. return DistanceJoint;
  27061. })(PhysicsJoint);
  27062. BABYLON.DistanceJoint = DistanceJoint;
  27063. var MotorEnabledJoint = (function (_super) {
  27064. __extends(MotorEnabledJoint, _super);
  27065. function MotorEnabledJoint(type, jointData) {
  27066. _super.call(this, type, jointData);
  27067. }
  27068. /**
  27069. * Set the motor values.
  27070. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27071. * @param {number} force the force to apply
  27072. * @param {number} maxForce max force for this motor.
  27073. */
  27074. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  27075. this._physicsPlugin.setMotor(this, force, maxForce);
  27076. };
  27077. /**
  27078. * Set the motor's limits.
  27079. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27080. */
  27081. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27082. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27083. };
  27084. return MotorEnabledJoint;
  27085. })(PhysicsJoint);
  27086. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  27087. /**
  27088. * This class represents a single hinge physics joint
  27089. */
  27090. var HingeJoint = (function (_super) {
  27091. __extends(HingeJoint, _super);
  27092. function HingeJoint(jointData) {
  27093. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  27094. }
  27095. /**
  27096. * Set the motor values.
  27097. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27098. * @param {number} force the force to apply
  27099. * @param {number} maxForce max force for this motor.
  27100. */
  27101. HingeJoint.prototype.setMotor = function (force, maxForce) {
  27102. this._physicsPlugin.setMotor(this, force, maxForce);
  27103. };
  27104. /**
  27105. * Set the motor's limits.
  27106. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27107. */
  27108. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27109. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27110. };
  27111. return HingeJoint;
  27112. })(MotorEnabledJoint);
  27113. BABYLON.HingeJoint = HingeJoint;
  27114. /**
  27115. * This class represents a dual hinge physics joint (same as wheel joint)
  27116. */
  27117. var Hinge2Joint = (function (_super) {
  27118. __extends(Hinge2Joint, _super);
  27119. function Hinge2Joint(jointData) {
  27120. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  27121. }
  27122. /**
  27123. * Set the motor values.
  27124. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27125. * @param {number} force the force to apply
  27126. * @param {number} maxForce max force for this motor.
  27127. * @param {motorIndex} the motor's index, 0 or 1.
  27128. */
  27129. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  27130. if (motorIndex === void 0) { motorIndex = 0; }
  27131. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  27132. };
  27133. /**
  27134. * Set the motor limits.
  27135. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27136. * @param {number} upperLimit the upper limit
  27137. * @param {number} lowerLimit lower limit
  27138. * @param {motorIndex} the motor's index, 0 or 1.
  27139. */
  27140. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  27141. if (motorIndex === void 0) { motorIndex = 0; }
  27142. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  27143. };
  27144. return Hinge2Joint;
  27145. })(MotorEnabledJoint);
  27146. BABYLON.Hinge2Joint = Hinge2Joint;
  27147. })(BABYLON || (BABYLON = {}));
  27148. var BABYLON;
  27149. (function (BABYLON) {
  27150. var PhysicsImpostor = (function () {
  27151. function PhysicsImpostor(object, type, _options, _scene) {
  27152. var _this = this;
  27153. if (_options === void 0) { _options = { mass: 0 }; }
  27154. this.object = object;
  27155. this.type = type;
  27156. this._options = _options;
  27157. this._scene = _scene;
  27158. this._bodyUpdateRequired = false;
  27159. this._onBeforePhysicsStepCallbacks = new Array();
  27160. this._onAfterPhysicsStepCallbacks = new Array();
  27161. this._onPhysicsCollideCallbacks = [];
  27162. this._deltaPosition = BABYLON.Vector3.Zero();
  27163. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  27164. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  27165. /**
  27166. * this function is executed by the physics engine.
  27167. */
  27168. this.beforeStep = function () {
  27169. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  27170. //conjugate deltaRotation
  27171. if (_this._deltaRotationConjugated) {
  27172. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  27173. }
  27174. else {
  27175. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  27176. }
  27177. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  27178. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  27179. func(_this);
  27180. });
  27181. };
  27182. /**
  27183. * this function is executed by the physics engine.
  27184. */
  27185. this.afterStep = function () {
  27186. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  27187. func(_this);
  27188. });
  27189. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  27190. _this.object.position.addInPlace(_this._deltaPosition);
  27191. if (_this._deltaRotation) {
  27192. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  27193. }
  27194. };
  27195. //event and body object due to cannon's event-based architecture.
  27196. this.onCollide = function (e) {
  27197. if (!_this._onPhysicsCollideCallbacks.length)
  27198. return;
  27199. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  27200. if (otherImpostor) {
  27201. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  27202. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  27203. }).forEach(function (obj) {
  27204. obj.callback(_this, otherImpostor);
  27205. });
  27206. }
  27207. };
  27208. //sanity check!
  27209. if (!this.object) {
  27210. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  27211. return;
  27212. }
  27213. //legacy support for old syntax.
  27214. if (!this._scene && object.getScene) {
  27215. this._scene = object.getScene();
  27216. }
  27217. this._physicsEngine = this._scene.getPhysicsEngine();
  27218. if (!this._physicsEngine) {
  27219. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  27220. }
  27221. else {
  27222. //set the object's quaternion, if not set
  27223. if (!this.object.rotationQuaternion) {
  27224. if (this.object.rotation) {
  27225. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  27226. }
  27227. else {
  27228. this.object.rotationQuaternion = new BABYLON.Quaternion();
  27229. }
  27230. }
  27231. //default options params
  27232. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  27233. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  27234. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  27235. this._joints = [];
  27236. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  27237. if (!this.object.parent) {
  27238. this._init();
  27239. }
  27240. }
  27241. }
  27242. /**
  27243. * This function will completly initialize this impostor.
  27244. * It will create a new body - but only if this mesh has no parent.
  27245. * If it has, this impostor will not be used other than to define the impostor
  27246. * of the child mesh.
  27247. */
  27248. PhysicsImpostor.prototype._init = function () {
  27249. this._physicsEngine.removeImpostor(this);
  27250. this.physicsBody = null;
  27251. this._parent = this._parent || this._getPhysicsParent();
  27252. if (!this.parent) {
  27253. this._physicsEngine.addImpostor(this);
  27254. }
  27255. };
  27256. PhysicsImpostor.prototype._getPhysicsParent = function () {
  27257. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  27258. var parentMesh = this.object.parent;
  27259. return parentMesh.physicsImpostor;
  27260. }
  27261. return;
  27262. };
  27263. /**
  27264. * Should a new body be generated.
  27265. */
  27266. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  27267. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  27268. };
  27269. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  27270. this.forceUpdate();
  27271. };
  27272. /**
  27273. * Force a regeneration of this or the parent's impostor's body.
  27274. * Use under cautious - This will remove all joints already implemented.
  27275. */
  27276. PhysicsImpostor.prototype.forceUpdate = function () {
  27277. this._init();
  27278. if (this.parent) {
  27279. this.parent.forceUpdate();
  27280. }
  27281. };
  27282. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  27283. /*public get mesh(): AbstractMesh {
  27284. return this._mesh;
  27285. }*/
  27286. /**
  27287. * Gets the body that holds this impostor. Either its own, or its parent.
  27288. */
  27289. get: function () {
  27290. return this._parent ? this._parent.physicsBody : this._physicsBody;
  27291. },
  27292. /**
  27293. * Set the physics body. Used mainly by the physics engine/plugin
  27294. */
  27295. set: function (physicsBody) {
  27296. if (this._physicsBody) {
  27297. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  27298. }
  27299. this._physicsBody = physicsBody;
  27300. this.resetUpdateFlags();
  27301. },
  27302. enumerable: true,
  27303. configurable: true
  27304. });
  27305. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  27306. get: function () {
  27307. return this._parent;
  27308. },
  27309. enumerable: true,
  27310. configurable: true
  27311. });
  27312. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  27313. this._bodyUpdateRequired = false;
  27314. };
  27315. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  27316. if (this.object.getBoundingInfo) {
  27317. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  27318. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  27319. }
  27320. else {
  27321. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  27322. }
  27323. };
  27324. PhysicsImpostor.prototype.getObjectCenter = function () {
  27325. if (this.object.getBoundingInfo) {
  27326. return this.object.getBoundingInfo().boundingBox.center;
  27327. }
  27328. else {
  27329. return this.object.position;
  27330. }
  27331. };
  27332. /**
  27333. * Get a specific parametes from the options parameter.
  27334. */
  27335. PhysicsImpostor.prototype.getParam = function (paramName) {
  27336. return this._options[paramName];
  27337. };
  27338. /**
  27339. * Sets a specific parameter in the options given to the physics plugin
  27340. */
  27341. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  27342. this._options[paramName] = value;
  27343. this._bodyUpdateRequired = true;
  27344. };
  27345. /**
  27346. * Specifically change the body's mass option. Won't recreate the physics body object
  27347. */
  27348. PhysicsImpostor.prototype.setMass = function (mass) {
  27349. if (this.getParam("mass") !== mass) {
  27350. this.setParam("mass", mass);
  27351. }
  27352. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  27353. };
  27354. PhysicsImpostor.prototype.getLinearVelocity = function () {
  27355. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  27356. };
  27357. /**
  27358. * Set the body's linear velocity.
  27359. */
  27360. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  27361. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  27362. };
  27363. PhysicsImpostor.prototype.getAngularVelocity = function () {
  27364. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  27365. };
  27366. /**
  27367. * Set the body's linear velocity.
  27368. */
  27369. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  27370. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  27371. };
  27372. /**
  27373. * Execute a function with the physics plugin native code.
  27374. * Provide a function the will have two variables - the world object and the physics body object.
  27375. */
  27376. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  27377. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  27378. };
  27379. /**
  27380. * Register a function that will be executed before the physics world is stepping forward.
  27381. */
  27382. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  27383. this._onBeforePhysicsStepCallbacks.push(func);
  27384. };
  27385. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  27386. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  27387. if (index > -1) {
  27388. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  27389. }
  27390. else {
  27391. BABYLON.Tools.Warn("Function to remove was not found");
  27392. }
  27393. };
  27394. /**
  27395. * Register a function that will be executed after the physics step
  27396. */
  27397. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  27398. this._onAfterPhysicsStepCallbacks.push(func);
  27399. };
  27400. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  27401. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  27402. if (index > -1) {
  27403. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  27404. }
  27405. else {
  27406. BABYLON.Tools.Warn("Function to remove was not found");
  27407. }
  27408. };
  27409. /**
  27410. * register a function that will be executed when this impostor collides against a different body.
  27411. */
  27412. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  27413. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27414. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  27415. };
  27416. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  27417. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27418. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  27419. if (index > -1) {
  27420. this._onPhysicsCollideCallbacks.splice(index, 1);
  27421. }
  27422. else {
  27423. BABYLON.Tools.Warn("Function to remove was not found");
  27424. }
  27425. };
  27426. /**
  27427. * Apply a force
  27428. */
  27429. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  27430. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  27431. };
  27432. /**
  27433. * Apply an impulse
  27434. */
  27435. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  27436. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  27437. };
  27438. /**
  27439. * A help function to create a joint.
  27440. */
  27441. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  27442. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  27443. this.addJoint(otherImpostor, joint);
  27444. };
  27445. /**
  27446. * Add a joint to this impostor with a different impostor.
  27447. */
  27448. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  27449. this._joints.push({
  27450. otherImpostor: otherImpostor,
  27451. joint: joint
  27452. });
  27453. this._physicsEngine.addJoint(this, otherImpostor, joint);
  27454. };
  27455. /**
  27456. * Will keep this body still, in a sleep mode.
  27457. */
  27458. PhysicsImpostor.prototype.sleep = function () {
  27459. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  27460. };
  27461. /**
  27462. * Wake the body up.
  27463. */
  27464. PhysicsImpostor.prototype.wakeUp = function () {
  27465. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  27466. };
  27467. PhysicsImpostor.prototype.clone = function (newObject) {
  27468. if (!newObject)
  27469. return null;
  27470. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  27471. };
  27472. PhysicsImpostor.prototype.dispose = function () {
  27473. var _this = this;
  27474. this._joints.forEach(function (j) {
  27475. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  27476. });
  27477. //dispose the physics body
  27478. this._physicsEngine.removeImpostor(this);
  27479. if (this.parent) {
  27480. this.parent.forceUpdate();
  27481. }
  27482. else {
  27483. }
  27484. };
  27485. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  27486. this._deltaPosition.copyFrom(position);
  27487. };
  27488. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  27489. if (!this._deltaRotation) {
  27490. this._deltaRotation = new BABYLON.Quaternion();
  27491. }
  27492. this._deltaRotation.copyFrom(rotation);
  27493. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  27494. };
  27495. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  27496. //Impostor types
  27497. PhysicsImpostor.NoImpostor = 0;
  27498. PhysicsImpostor.SphereImpostor = 1;
  27499. PhysicsImpostor.BoxImpostor = 2;
  27500. PhysicsImpostor.PlaneImpostor = 3;
  27501. PhysicsImpostor.MeshImpostor = 4;
  27502. PhysicsImpostor.CylinderImpostor = 7;
  27503. PhysicsImpostor.ParticleImpostor = 8;
  27504. PhysicsImpostor.HeightmapImpostor = 9;
  27505. return PhysicsImpostor;
  27506. })();
  27507. BABYLON.PhysicsImpostor = PhysicsImpostor;
  27508. })(BABYLON || (BABYLON = {}));
  27509. var BABYLON;
  27510. (function (BABYLON) {
  27511. var PhysicsEngine = (function () {
  27512. function PhysicsEngine(gravity, _physicsPlugin) {
  27513. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  27514. this._physicsPlugin = _physicsPlugin;
  27515. //new methods and parameters
  27516. this._impostors = [];
  27517. this._joints = [];
  27518. if (!this._physicsPlugin.isSupported()) {
  27519. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  27520. + "Please make sure it is included.");
  27521. }
  27522. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  27523. this.setGravity(gravity);
  27524. this.setTimeStep();
  27525. }
  27526. PhysicsEngine.prototype.setGravity = function (gravity) {
  27527. this.gravity = gravity;
  27528. this._physicsPlugin.setGravity(this.gravity);
  27529. };
  27530. /**
  27531. * Set the time step of the physics engine.
  27532. * default is 1/60.
  27533. * To slow it down, enter 1/600 for example.
  27534. * To speed it up, 1/30
  27535. * @param {number} newTimeStep the new timestep to apply to this world.
  27536. */
  27537. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  27538. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  27539. this._physicsPlugin.setTimeStep(newTimeStep);
  27540. };
  27541. PhysicsEngine.prototype.dispose = function () {
  27542. this._impostors.forEach(function (impostor) {
  27543. impostor.dispose();
  27544. });
  27545. this._physicsPlugin.dispose();
  27546. };
  27547. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  27548. return this._physicsPlugin.name;
  27549. };
  27550. /**
  27551. * Adding a new impostor for the impostor tracking.
  27552. * This will be done by the impostor itself.
  27553. * @param {PhysicsImpostor} impostor the impostor to add
  27554. */
  27555. PhysicsEngine.prototype.addImpostor = function (impostor) {
  27556. impostor.uniqueId = this._impostors.push(impostor);
  27557. //if no parent, generate the body
  27558. if (!impostor.parent) {
  27559. this._physicsPlugin.generatePhysicsBody(impostor);
  27560. }
  27561. };
  27562. /**
  27563. * Remove an impostor from the engine.
  27564. * This impostor and its mesh will not longer be updated by the physics engine.
  27565. * @param {PhysicsImpostor} impostor the impostor to remove
  27566. */
  27567. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  27568. var index = this._impostors.indexOf(impostor);
  27569. if (index > -1) {
  27570. var removed = this._impostors.splice(index, 1);
  27571. //Is it needed?
  27572. if (removed.length) {
  27573. //this will also remove it from the world.
  27574. removed[0].physicsBody = null;
  27575. }
  27576. }
  27577. };
  27578. /**
  27579. * Add a joint to the physics engine
  27580. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  27581. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  27582. * @param {PhysicsJoint} the joint that will connect both impostors.
  27583. */
  27584. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  27585. var impostorJoint = {
  27586. mainImpostor: mainImpostor,
  27587. connectedImpostor: connectedImpostor,
  27588. joint: joint
  27589. };
  27590. joint.physicsPlugin = this._physicsPlugin;
  27591. this._joints.push(impostorJoint);
  27592. this._physicsPlugin.generateJoint(impostorJoint);
  27593. };
  27594. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  27595. var matchingJoints = this._joints.filter(function (impostorJoint) {
  27596. return (impostorJoint.connectedImpostor === connectedImpostor
  27597. && impostorJoint.joint === joint
  27598. && impostorJoint.mainImpostor === mainImpostor);
  27599. });
  27600. if (matchingJoints.length) {
  27601. this._physicsPlugin.removeJoint(matchingJoints[0]);
  27602. }
  27603. };
  27604. /**
  27605. * Called by the scene. no need to call it.
  27606. */
  27607. PhysicsEngine.prototype._step = function (delta) {
  27608. var _this = this;
  27609. //check if any mesh has no body / requires an update
  27610. this._impostors.forEach(function (impostor) {
  27611. if (impostor.isBodyInitRequired()) {
  27612. _this._physicsPlugin.generatePhysicsBody(impostor);
  27613. }
  27614. });
  27615. if (delta > 0.1) {
  27616. delta = 0.1;
  27617. }
  27618. else if (delta <= 0) {
  27619. delta = 1.0 / 60.0;
  27620. }
  27621. this._physicsPlugin.executeStep(delta, this._impostors);
  27622. };
  27623. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  27624. return this._physicsPlugin;
  27625. };
  27626. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  27627. for (var i = 0; i < this._impostors.length; ++i) {
  27628. if (this._impostors[i].object === object) {
  27629. return this._impostors[i];
  27630. }
  27631. }
  27632. };
  27633. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  27634. for (var i = 0; i < this._impostors.length; ++i) {
  27635. if (this._impostors[i].physicsBody === body) {
  27636. return this._impostors[i];
  27637. }
  27638. }
  27639. };
  27640. // Statics, Legacy support.
  27641. /**
  27642. * @Deprecated
  27643. *
  27644. */
  27645. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  27646. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  27647. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  27648. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  27649. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  27650. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  27651. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  27652. PhysicsEngine.CapsuleImpostor = -1;
  27653. PhysicsEngine.ConeImpostor = -1;
  27654. PhysicsEngine.ConvexHullImpostor = -1;
  27655. PhysicsEngine.Epsilon = 0.001;
  27656. return PhysicsEngine;
  27657. })();
  27658. BABYLON.PhysicsEngine = PhysicsEngine;
  27659. })(BABYLON || (BABYLON = {}));
  27660. var BABYLON;
  27661. (function (BABYLON) {
  27662. var VertexData = (function () {
  27663. function VertexData() {
  27664. }
  27665. VertexData.prototype.set = function (data, kind) {
  27666. switch (kind) {
  27667. case BABYLON.VertexBuffer.PositionKind:
  27668. this.positions = data;
  27669. break;
  27670. case BABYLON.VertexBuffer.NormalKind:
  27671. this.normals = data;
  27672. break;
  27673. case BABYLON.VertexBuffer.UVKind:
  27674. this.uvs = data;
  27675. break;
  27676. case BABYLON.VertexBuffer.UV2Kind:
  27677. this.uvs2 = data;
  27678. break;
  27679. case BABYLON.VertexBuffer.UV3Kind:
  27680. this.uvs3 = data;
  27681. break;
  27682. case BABYLON.VertexBuffer.UV4Kind:
  27683. this.uvs4 = data;
  27684. break;
  27685. case BABYLON.VertexBuffer.UV5Kind:
  27686. this.uvs5 = data;
  27687. break;
  27688. case BABYLON.VertexBuffer.UV6Kind:
  27689. this.uvs6 = data;
  27690. break;
  27691. case BABYLON.VertexBuffer.ColorKind:
  27692. this.colors = data;
  27693. break;
  27694. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27695. this.matricesIndices = data;
  27696. break;
  27697. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27698. this.matricesWeights = data;
  27699. break;
  27700. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27701. this.matricesIndicesExtra = data;
  27702. break;
  27703. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27704. this.matricesWeightsExtra = data;
  27705. break;
  27706. }
  27707. };
  27708. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27709. this._applyTo(mesh, updatable);
  27710. };
  27711. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27712. this._applyTo(geometry, updatable);
  27713. };
  27714. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27715. this._update(mesh);
  27716. };
  27717. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27718. this._update(geometry);
  27719. };
  27720. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27721. if (this.positions) {
  27722. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27723. }
  27724. if (this.normals) {
  27725. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27726. }
  27727. if (this.uvs) {
  27728. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27729. }
  27730. if (this.uvs2) {
  27731. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27732. }
  27733. if (this.uvs3) {
  27734. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27735. }
  27736. if (this.uvs4) {
  27737. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27738. }
  27739. if (this.uvs5) {
  27740. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27741. }
  27742. if (this.uvs6) {
  27743. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27744. }
  27745. if (this.colors) {
  27746. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27747. }
  27748. if (this.matricesIndices) {
  27749. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27750. }
  27751. if (this.matricesWeights) {
  27752. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27753. }
  27754. if (this.matricesIndicesExtra) {
  27755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27756. }
  27757. if (this.matricesWeightsExtra) {
  27758. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27759. }
  27760. if (this.indices) {
  27761. meshOrGeometry.setIndices(this.indices);
  27762. }
  27763. };
  27764. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27765. if (this.positions) {
  27766. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27767. }
  27768. if (this.normals) {
  27769. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27770. }
  27771. if (this.uvs) {
  27772. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27773. }
  27774. if (this.uvs2) {
  27775. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27776. }
  27777. if (this.uvs3) {
  27778. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27779. }
  27780. if (this.uvs4) {
  27781. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27782. }
  27783. if (this.uvs5) {
  27784. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27785. }
  27786. if (this.uvs6) {
  27787. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27788. }
  27789. if (this.colors) {
  27790. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27791. }
  27792. if (this.matricesIndices) {
  27793. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27794. }
  27795. if (this.matricesWeights) {
  27796. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27797. }
  27798. if (this.matricesIndicesExtra) {
  27799. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27800. }
  27801. if (this.matricesWeightsExtra) {
  27802. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27803. }
  27804. if (this.indices) {
  27805. meshOrGeometry.setIndices(this.indices);
  27806. }
  27807. };
  27808. VertexData.prototype.transform = function (matrix) {
  27809. var transformed = BABYLON.Vector3.Zero();
  27810. var index;
  27811. if (this.positions) {
  27812. var position = BABYLON.Vector3.Zero();
  27813. for (index = 0; index < this.positions.length; index += 3) {
  27814. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27815. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27816. this.positions[index] = transformed.x;
  27817. this.positions[index + 1] = transformed.y;
  27818. this.positions[index + 2] = transformed.z;
  27819. }
  27820. }
  27821. if (this.normals) {
  27822. var normal = BABYLON.Vector3.Zero();
  27823. for (index = 0; index < this.normals.length; index += 3) {
  27824. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27825. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27826. this.normals[index] = transformed.x;
  27827. this.normals[index + 1] = transformed.y;
  27828. this.normals[index + 2] = transformed.z;
  27829. }
  27830. }
  27831. };
  27832. VertexData.prototype.merge = function (other) {
  27833. if (other.indices) {
  27834. if (!this.indices) {
  27835. this.indices = [];
  27836. }
  27837. var offset = this.positions ? this.positions.length / 3 : 0;
  27838. for (var index = 0; index < other.indices.length; index++) {
  27839. //TODO check type - if Int32Array!
  27840. this.indices.push(other.indices[index] + offset);
  27841. }
  27842. }
  27843. this.positions = this._mergeElement(this.positions, other.positions);
  27844. this.normals = this._mergeElement(this.normals, other.normals);
  27845. this.uvs = this._mergeElement(this.uvs, other.uvs);
  27846. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  27847. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  27848. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  27849. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  27850. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  27851. this.colors = this._mergeElement(this.colors, other.colors);
  27852. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  27853. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  27854. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  27855. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  27856. };
  27857. VertexData.prototype._mergeElement = function (source, other) {
  27858. if (!other)
  27859. return source;
  27860. if (!source)
  27861. return other;
  27862. var len = other.length + source.length;
  27863. var isSrcTypedArray = source instanceof Float32Array;
  27864. var isOthTypedArray = other instanceof Float32Array;
  27865. // use non-loop method when the source is Float32Array
  27866. if (isSrcTypedArray) {
  27867. var ret32 = new Float32Array(len);
  27868. ret32.set(source);
  27869. ret32.set(other, source.length);
  27870. return ret32;
  27871. }
  27872. else if (!isOthTypedArray) {
  27873. return source.concat(other);
  27874. }
  27875. else {
  27876. var ret = source.slice(0); // copy source to a separate array
  27877. for (var i = 0, len = other.length; i < len; i++) {
  27878. ret.push(other[i]);
  27879. }
  27880. return ret;
  27881. }
  27882. };
  27883. VertexData.prototype.serialize = function () {
  27884. var serializationObject = this.serialize();
  27885. if (this.positions) {
  27886. serializationObject.positions = this.positions;
  27887. }
  27888. if (this.normals) {
  27889. serializationObject.normals = this.normals;
  27890. }
  27891. if (this.uvs) {
  27892. serializationObject.uvs = this.uvs;
  27893. }
  27894. if (this.uvs2) {
  27895. serializationObject.uvs2 = this.uvs2;
  27896. }
  27897. if (this.uvs3) {
  27898. serializationObject.uvs3 = this.uvs3;
  27899. }
  27900. if (this.uvs4) {
  27901. serializationObject.uvs4 = this.uvs4;
  27902. }
  27903. if (this.uvs5) {
  27904. serializationObject.uvs5 = this.uvs5;
  27905. }
  27906. if (this.uvs6) {
  27907. serializationObject.uvs6 = this.uvs6;
  27908. }
  27909. if (this.colors) {
  27910. serializationObject.colors = this.colors;
  27911. }
  27912. if (this.matricesIndices) {
  27913. serializationObject.matricesIndices = this.matricesIndices;
  27914. serializationObject.matricesIndices._isExpanded = true;
  27915. }
  27916. if (this.matricesWeights) {
  27917. serializationObject.matricesWeights = this.matricesWeights;
  27918. }
  27919. if (this.matricesIndicesExtra) {
  27920. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27921. serializationObject.matricesIndicesExtra._isExpanded = true;
  27922. }
  27923. if (this.matricesWeightsExtra) {
  27924. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27925. }
  27926. serializationObject.indices = this.indices;
  27927. return serializationObject;
  27928. };
  27929. // Statics
  27930. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  27931. return VertexData._ExtractFrom(mesh, copyWhenShared);
  27932. };
  27933. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  27934. return VertexData._ExtractFrom(geometry, copyWhenShared);
  27935. };
  27936. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  27937. var result = new VertexData();
  27938. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27939. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  27940. }
  27941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27942. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  27943. }
  27944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27945. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  27946. }
  27947. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27948. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  27949. }
  27950. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27951. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  27952. }
  27953. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27954. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  27955. }
  27956. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27957. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  27958. }
  27959. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27960. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  27961. }
  27962. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27963. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  27964. }
  27965. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27966. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  27967. }
  27968. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27969. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  27970. }
  27971. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27972. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  27973. }
  27974. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27975. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  27976. }
  27977. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27978. return result;
  27979. };
  27980. VertexData.CreateRibbon = function (options) {
  27981. var pathArray = options.pathArray;
  27982. var closeArray = options.closeArray || false;
  27983. var closePath = options.closePath || false;
  27984. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27985. var offset = options.offset || defaultOffset;
  27986. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27987. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27988. var positions = [];
  27989. var indices = [];
  27990. var normals = [];
  27991. var uvs = [];
  27992. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27993. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27994. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27995. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27996. var minlg; // minimal length among all paths from pathArray
  27997. var lg = []; // array of path lengths : nb of vertex per path
  27998. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27999. var p; // path iterator
  28000. var i; // point iterator
  28001. var j; // point iterator
  28002. // if single path in pathArray
  28003. if (pathArray.length < 2) {
  28004. var ar1 = [];
  28005. var ar2 = [];
  28006. for (i = 0; i < pathArray[0].length - offset; i++) {
  28007. ar1.push(pathArray[0][i]);
  28008. ar2.push(pathArray[0][i + offset]);
  28009. }
  28010. pathArray = [ar1, ar2];
  28011. }
  28012. // positions and horizontal distances (u)
  28013. var idc = 0;
  28014. var closePathCorr = (closePath) ? 1 : 0;
  28015. var path;
  28016. var l;
  28017. minlg = pathArray[0].length;
  28018. var vectlg;
  28019. var dist;
  28020. for (p = 0; p < pathArray.length; p++) {
  28021. uTotalDistance[p] = 0;
  28022. us[p] = [0];
  28023. path = pathArray[p];
  28024. l = path.length;
  28025. minlg = (minlg < l) ? minlg : l;
  28026. j = 0;
  28027. while (j < l) {
  28028. positions.push(path[j].x, path[j].y, path[j].z);
  28029. if (j > 0) {
  28030. vectlg = path[j].subtract(path[j - 1]).length();
  28031. dist = vectlg + uTotalDistance[p];
  28032. us[p].push(dist);
  28033. uTotalDistance[p] = dist;
  28034. }
  28035. j++;
  28036. }
  28037. if (closePath) {
  28038. j--;
  28039. positions.push(path[0].x, path[0].y, path[0].z);
  28040. vectlg = path[j].subtract(path[0]).length();
  28041. dist = vectlg + uTotalDistance[p];
  28042. us[p].push(dist);
  28043. uTotalDistance[p] = dist;
  28044. }
  28045. lg[p] = l + closePathCorr;
  28046. idx[p] = idc;
  28047. idc += (l + closePathCorr);
  28048. }
  28049. // vertical distances (v)
  28050. var path1;
  28051. var path2;
  28052. var vertex1;
  28053. var vertex2;
  28054. for (i = 0; i < minlg + closePathCorr; i++) {
  28055. vTotalDistance[i] = 0;
  28056. vs[i] = [0];
  28057. for (p = 0; p < pathArray.length - 1; p++) {
  28058. path1 = pathArray[p];
  28059. path2 = pathArray[p + 1];
  28060. if (i === minlg) {
  28061. vertex1 = path1[0];
  28062. vertex2 = path2[0];
  28063. }
  28064. else {
  28065. vertex1 = path1[i];
  28066. vertex2 = path2[i];
  28067. }
  28068. vectlg = vertex2.subtract(vertex1).length();
  28069. dist = vectlg + vTotalDistance[i];
  28070. vs[i].push(dist);
  28071. vTotalDistance[i] = dist;
  28072. }
  28073. if (closeArray) {
  28074. path1 = pathArray[p];
  28075. path2 = pathArray[0];
  28076. if (i === minlg) {
  28077. vertex2 = path2[0];
  28078. }
  28079. vectlg = vertex2.subtract(vertex1).length();
  28080. dist = vectlg + vTotalDistance[i];
  28081. vTotalDistance[i] = dist;
  28082. }
  28083. }
  28084. // uvs
  28085. var u;
  28086. var v;
  28087. for (p = 0; p < pathArray.length; p++) {
  28088. for (i = 0; i < minlg + closePathCorr; i++) {
  28089. u = us[p][i] / uTotalDistance[p];
  28090. v = vs[i][p] / vTotalDistance[i];
  28091. uvs.push(u, v);
  28092. }
  28093. }
  28094. // indices
  28095. p = 0; // path index
  28096. var pi = 0; // positions array index
  28097. var l1 = lg[p] - 1; // path1 length
  28098. var l2 = lg[p + 1] - 1; // path2 length
  28099. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28100. var shft = idx[1] - idx[0]; // shift
  28101. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28102. while (pi <= min && p < path1nb) {
  28103. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  28104. indices.push(pi, pi + shft, pi + 1);
  28105. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28106. pi += 1;
  28107. if (pi === min) {
  28108. p++;
  28109. if (p === lg.length - 1) {
  28110. shft = idx[0] - idx[p];
  28111. l1 = lg[p] - 1;
  28112. l2 = lg[0] - 1;
  28113. }
  28114. else {
  28115. shft = idx[p + 1] - idx[p];
  28116. l1 = lg[p] - 1;
  28117. l2 = lg[p + 1] - 1;
  28118. }
  28119. pi = idx[p];
  28120. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28121. }
  28122. }
  28123. // normals
  28124. VertexData.ComputeNormals(positions, indices, normals);
  28125. if (closePath) {
  28126. var indexFirst = 0;
  28127. var indexLast = 0;
  28128. for (p = 0; p < pathArray.length; p++) {
  28129. indexFirst = idx[p] * 3;
  28130. if (p + 1 < pathArray.length) {
  28131. indexLast = (idx[p + 1] - 1) * 3;
  28132. }
  28133. else {
  28134. indexLast = normals.length - 3;
  28135. }
  28136. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28137. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28138. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28139. normals[indexLast] = normals[indexFirst];
  28140. normals[indexLast + 1] = normals[indexFirst + 1];
  28141. normals[indexLast + 2] = normals[indexFirst + 2];
  28142. }
  28143. }
  28144. // sides
  28145. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28146. // Result
  28147. var vertexData = new VertexData();
  28148. vertexData.indices = indices;
  28149. vertexData.positions = positions;
  28150. vertexData.normals = normals;
  28151. vertexData.uvs = uvs;
  28152. if (closePath) {
  28153. vertexData._idx = idx;
  28154. }
  28155. return vertexData;
  28156. };
  28157. VertexData.CreateBox = function (options) {
  28158. var normalsSource = [
  28159. new BABYLON.Vector3(0, 0, 1),
  28160. new BABYLON.Vector3(0, 0, -1),
  28161. new BABYLON.Vector3(1, 0, 0),
  28162. new BABYLON.Vector3(-1, 0, 0),
  28163. new BABYLON.Vector3(0, 1, 0),
  28164. new BABYLON.Vector3(0, -1, 0)
  28165. ];
  28166. var indices = [];
  28167. var positions = [];
  28168. var normals = [];
  28169. var uvs = [];
  28170. var width = options.width || options.size || 1;
  28171. var height = options.height || options.size || 1;
  28172. var depth = options.depth || options.size || 1;
  28173. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28174. var faceUV = options.faceUV || new Array(6);
  28175. var faceColors = options.faceColors;
  28176. var colors = [];
  28177. // default face colors and UV if undefined
  28178. for (var f = 0; f < 6; f++) {
  28179. if (faceUV[f] === undefined) {
  28180. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28181. }
  28182. if (faceColors && faceColors[f] === undefined) {
  28183. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28184. }
  28185. }
  28186. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28187. // Create each face in turn.
  28188. for (var index = 0; index < normalsSource.length; index++) {
  28189. var normal = normalsSource[index];
  28190. // Get two vectors perpendicular to the face normal and to each other.
  28191. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28192. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28193. // Six indices (two triangles) per face.
  28194. var verticesLength = positions.length / 3;
  28195. indices.push(verticesLength);
  28196. indices.push(verticesLength + 1);
  28197. indices.push(verticesLength + 2);
  28198. indices.push(verticesLength);
  28199. indices.push(verticesLength + 2);
  28200. indices.push(verticesLength + 3);
  28201. // Four vertices per face.
  28202. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28203. positions.push(vertex.x, vertex.y, vertex.z);
  28204. normals.push(normal.x, normal.y, normal.z);
  28205. uvs.push(faceUV[index].z, faceUV[index].w);
  28206. if (faceColors) {
  28207. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28208. }
  28209. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28210. positions.push(vertex.x, vertex.y, vertex.z);
  28211. normals.push(normal.x, normal.y, normal.z);
  28212. uvs.push(faceUV[index].x, faceUV[index].w);
  28213. if (faceColors) {
  28214. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28215. }
  28216. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28217. positions.push(vertex.x, vertex.y, vertex.z);
  28218. normals.push(normal.x, normal.y, normal.z);
  28219. uvs.push(faceUV[index].x, faceUV[index].y);
  28220. if (faceColors) {
  28221. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28222. }
  28223. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28224. positions.push(vertex.x, vertex.y, vertex.z);
  28225. normals.push(normal.x, normal.y, normal.z);
  28226. uvs.push(faceUV[index].z, faceUV[index].y);
  28227. if (faceColors) {
  28228. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28229. }
  28230. }
  28231. // sides
  28232. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28233. // Result
  28234. var vertexData = new VertexData();
  28235. vertexData.indices = indices;
  28236. vertexData.positions = positions;
  28237. vertexData.normals = normals;
  28238. vertexData.uvs = uvs;
  28239. if (faceColors) {
  28240. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28241. vertexData.colors = totalColors;
  28242. }
  28243. return vertexData;
  28244. };
  28245. VertexData.CreateSphere = function (options) {
  28246. var segments = options.segments || 32;
  28247. var diameterX = options.diameterX || options.diameter || 1;
  28248. var diameterY = options.diameterY || options.diameter || 1;
  28249. var diameterZ = options.diameterZ || options.diameter || 1;
  28250. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28251. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28252. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28253. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28254. var totalZRotationSteps = 2 + segments;
  28255. var totalYRotationSteps = 2 * totalZRotationSteps;
  28256. var indices = [];
  28257. var positions = [];
  28258. var normals = [];
  28259. var uvs = [];
  28260. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28261. var normalizedZ = zRotationStep / totalZRotationSteps;
  28262. var angleZ = normalizedZ * Math.PI * slice;
  28263. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28264. var normalizedY = yRotationStep / totalYRotationSteps;
  28265. var angleY = normalizedY * Math.PI * 2 * arc;
  28266. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28267. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28268. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28269. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28270. var vertex = complete.multiply(radius);
  28271. var normal = complete.divide(radius).normalize();
  28272. positions.push(vertex.x, vertex.y, vertex.z);
  28273. normals.push(normal.x, normal.y, normal.z);
  28274. uvs.push(normalizedY, normalizedZ);
  28275. }
  28276. if (zRotationStep > 0) {
  28277. var verticesCount = positions.length / 3;
  28278. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28279. indices.push((firstIndex));
  28280. indices.push((firstIndex + 1));
  28281. indices.push(firstIndex + totalYRotationSteps + 1);
  28282. indices.push((firstIndex + totalYRotationSteps + 1));
  28283. indices.push((firstIndex + 1));
  28284. indices.push((firstIndex + totalYRotationSteps + 2));
  28285. }
  28286. }
  28287. }
  28288. // Sides
  28289. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28290. // Result
  28291. var vertexData = new VertexData();
  28292. vertexData.indices = indices;
  28293. vertexData.positions = positions;
  28294. vertexData.normals = normals;
  28295. vertexData.uvs = uvs;
  28296. return vertexData;
  28297. };
  28298. // Cylinder and cone
  28299. VertexData.CreateCylinder = function (options) {
  28300. var height = options.height || 2;
  28301. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28302. var diameterBottom = options.diameterBottom || options.diameter || 1;
  28303. var tessellation = options.tessellation || 24;
  28304. var subdivisions = options.subdivisions || 1;
  28305. var hasRings = options.hasRings;
  28306. var enclose = options.enclose;
  28307. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28308. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28309. var faceUV = options.faceUV || new Array(3);
  28310. var faceColors = options.faceColors;
  28311. // default face colors and UV if undefined
  28312. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28313. var ringNb = (hasRings) ? subdivisions : 1;
  28314. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28315. var f;
  28316. for (f = 0; f < surfaceNb; f++) {
  28317. if (faceColors && faceColors[f] === undefined) {
  28318. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28319. }
  28320. }
  28321. for (f = 0; f < surfaceNb; f++) {
  28322. if (faceUV && faceUV[f] === undefined) {
  28323. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28324. }
  28325. }
  28326. var indices = [];
  28327. var positions = [];
  28328. var normals = [];
  28329. var uvs = [];
  28330. var colors = [];
  28331. var angle_step = Math.PI * 2 * arc / tessellation;
  28332. var angle;
  28333. var h;
  28334. var radius;
  28335. var tan = (diameterBottom - diameterTop) / 2 / height;
  28336. var ringVertex = BABYLON.Vector3.Zero();
  28337. var ringNormal = BABYLON.Vector3.Zero();
  28338. var ringFirstVertex = BABYLON.Vector3.Zero();
  28339. var ringFirstNormal = BABYLON.Vector3.Zero();
  28340. var quadNormal = BABYLON.Vector3.Zero();
  28341. var Y = BABYLON.Axis.Y;
  28342. // positions, normals, uvs
  28343. var i;
  28344. var j;
  28345. var r;
  28346. var ringIdx = 1;
  28347. var s = 1; // surface index
  28348. var cs = 0;
  28349. var v = 0;
  28350. for (i = 0; i <= subdivisions; i++) {
  28351. h = i / subdivisions;
  28352. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28353. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28354. for (r = 0; r < ringIdx; r++) {
  28355. if (hasRings) {
  28356. s += r;
  28357. }
  28358. if (enclose) {
  28359. s += 2 * r;
  28360. }
  28361. for (j = 0; j <= tessellation; j++) {
  28362. angle = j * angle_step;
  28363. // position
  28364. ringVertex.x = Math.cos(-angle) * radius;
  28365. ringVertex.y = -height / 2 + h * height;
  28366. ringVertex.z = Math.sin(-angle) * radius;
  28367. // normal
  28368. if (diameterTop === 0 && i === subdivisions) {
  28369. // if no top cap, reuse former normals
  28370. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28371. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28372. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28373. }
  28374. else {
  28375. ringNormal.x = ringVertex.x;
  28376. ringNormal.z = ringVertex.z;
  28377. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28378. ringNormal.normalize();
  28379. }
  28380. // keep first ring vertex values for enclose
  28381. if (j === 0) {
  28382. ringFirstVertex.copyFrom(ringVertex);
  28383. ringFirstNormal.copyFrom(ringNormal);
  28384. }
  28385. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28386. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28387. if (hasRings) {
  28388. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28389. }
  28390. else {
  28391. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28392. }
  28393. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28394. if (faceColors) {
  28395. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28396. }
  28397. }
  28398. // if enclose, add four vertices and their dedicated normals
  28399. if (arc !== 1 && enclose) {
  28400. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28401. positions.push(0, ringVertex.y, 0);
  28402. positions.push(0, ringVertex.y, 0);
  28403. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28404. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28405. quadNormal.normalize();
  28406. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28407. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28408. quadNormal.normalize();
  28409. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28410. if (hasRings) {
  28411. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28412. }
  28413. else {
  28414. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28415. }
  28416. uvs.push(faceUV[s + 1].x, v);
  28417. uvs.push(faceUV[s + 1].z, v);
  28418. if (hasRings) {
  28419. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28420. }
  28421. else {
  28422. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28423. }
  28424. uvs.push(faceUV[s + 2].x, v);
  28425. uvs.push(faceUV[s + 2].z, v);
  28426. if (faceColors) {
  28427. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28428. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28429. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28430. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28431. }
  28432. }
  28433. if (cs !== s) {
  28434. cs = s;
  28435. }
  28436. }
  28437. }
  28438. // indices
  28439. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28440. var s;
  28441. i = 0;
  28442. for (s = 0; s < subdivisions; s++) {
  28443. for (j = 0; j < tessellation; j++) {
  28444. var i0 = i * (e + 1) + j;
  28445. var i1 = (i + 1) * (e + 1) + j;
  28446. var i2 = i * (e + 1) + (j + 1);
  28447. var i3 = (i + 1) * (e + 1) + (j + 1);
  28448. indices.push(i0, i1, i2);
  28449. indices.push(i3, i2, i1);
  28450. }
  28451. if (arc !== 1 && enclose) {
  28452. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28453. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28454. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28455. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28456. }
  28457. i = (hasRings) ? (i + 2) : (i + 1);
  28458. }
  28459. // Caps
  28460. var createCylinderCap = function (isTop) {
  28461. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28462. if (radius === 0) {
  28463. return;
  28464. }
  28465. // Cap positions, normals & uvs
  28466. var angle;
  28467. var circleVector;
  28468. var i;
  28469. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28470. var c;
  28471. if (faceColors) {
  28472. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28473. }
  28474. // cap center
  28475. var vbase = positions.length / 3;
  28476. var offset = isTop ? height / 2 : -height / 2;
  28477. var center = new BABYLON.Vector3(0, offset, 0);
  28478. positions.push(center.x, center.y, center.z);
  28479. normals.push(0, isTop ? 1 : -1, 0);
  28480. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28481. if (faceColors) {
  28482. colors.push(c.r, c.g, c.b, c.a);
  28483. }
  28484. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28485. for (i = 0; i <= tessellation; i++) {
  28486. angle = Math.PI * 2 * i * arc / tessellation;
  28487. var cos = Math.cos(-angle);
  28488. var sin = Math.sin(-angle);
  28489. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28490. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28491. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28492. normals.push(0, isTop ? 1 : -1, 0);
  28493. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28494. if (faceColors) {
  28495. colors.push(c.r, c.g, c.b, c.a);
  28496. }
  28497. }
  28498. // Cap indices
  28499. for (i = 0; i < tessellation; i++) {
  28500. if (!isTop) {
  28501. indices.push(vbase);
  28502. indices.push(vbase + (i + 1));
  28503. indices.push(vbase + (i + 2));
  28504. }
  28505. else {
  28506. indices.push(vbase);
  28507. indices.push(vbase + (i + 2));
  28508. indices.push(vbase + (i + 1));
  28509. }
  28510. }
  28511. };
  28512. // add caps to geometry
  28513. createCylinderCap(false);
  28514. createCylinderCap(true);
  28515. // Sides
  28516. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28517. var vertexData = new VertexData();
  28518. vertexData.indices = indices;
  28519. vertexData.positions = positions;
  28520. vertexData.normals = normals;
  28521. vertexData.uvs = uvs;
  28522. if (faceColors) {
  28523. vertexData.colors = colors;
  28524. }
  28525. return vertexData;
  28526. };
  28527. VertexData.CreateTorus = function (options) {
  28528. var indices = [];
  28529. var positions = [];
  28530. var normals = [];
  28531. var uvs = [];
  28532. var diameter = options.diameter || 1;
  28533. var thickness = options.thickness || 0.5;
  28534. var tessellation = options.tessellation || 16;
  28535. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28536. var stride = tessellation + 1;
  28537. for (var i = 0; i <= tessellation; i++) {
  28538. var u = i / tessellation;
  28539. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28540. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28541. for (var j = 0; j <= tessellation; j++) {
  28542. var v = 1 - j / tessellation;
  28543. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28544. var dx = Math.cos(innerAngle);
  28545. var dy = Math.sin(innerAngle);
  28546. // Create a vertex.
  28547. var normal = new BABYLON.Vector3(dx, dy, 0);
  28548. var position = normal.scale(thickness / 2);
  28549. var textureCoordinate = new BABYLON.Vector2(u, v);
  28550. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28551. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28552. positions.push(position.x, position.y, position.z);
  28553. normals.push(normal.x, normal.y, normal.z);
  28554. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28555. // And create indices for two triangles.
  28556. var nextI = (i + 1) % stride;
  28557. var nextJ = (j + 1) % stride;
  28558. indices.push(i * stride + j);
  28559. indices.push(i * stride + nextJ);
  28560. indices.push(nextI * stride + j);
  28561. indices.push(i * stride + nextJ);
  28562. indices.push(nextI * stride + nextJ);
  28563. indices.push(nextI * stride + j);
  28564. }
  28565. }
  28566. // Sides
  28567. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28568. // Result
  28569. var vertexData = new VertexData();
  28570. vertexData.indices = indices;
  28571. vertexData.positions = positions;
  28572. vertexData.normals = normals;
  28573. vertexData.uvs = uvs;
  28574. return vertexData;
  28575. };
  28576. VertexData.CreateLineSystem = function (options) {
  28577. var indices = [];
  28578. var positions = [];
  28579. var lines = options.lines;
  28580. var idx = 0;
  28581. for (var l = 0; l < lines.length; l++) {
  28582. var points = lines[l];
  28583. for (var index = 0; index < points.length; index++) {
  28584. positions.push(points[index].x, points[index].y, points[index].z);
  28585. if (index > 0) {
  28586. indices.push(idx - 1);
  28587. indices.push(idx);
  28588. }
  28589. idx++;
  28590. }
  28591. }
  28592. var vertexData = new VertexData();
  28593. vertexData.indices = indices;
  28594. vertexData.positions = positions;
  28595. return vertexData;
  28596. };
  28597. VertexData.CreateDashedLines = function (options) {
  28598. var dashSize = options.dashSize || 3;
  28599. var gapSize = options.gapSize || 1;
  28600. var dashNb = options.dashNb || 200;
  28601. var points = options.points;
  28602. var positions = new Array();
  28603. var indices = new Array();
  28604. var curvect = BABYLON.Vector3.Zero();
  28605. var lg = 0;
  28606. var nb = 0;
  28607. var shft = 0;
  28608. var dashshft = 0;
  28609. var curshft = 0;
  28610. var idx = 0;
  28611. var i = 0;
  28612. for (i = 0; i < points.length - 1; i++) {
  28613. points[i + 1].subtractToRef(points[i], curvect);
  28614. lg += curvect.length();
  28615. }
  28616. shft = lg / dashNb;
  28617. dashshft = dashSize * shft / (dashSize + gapSize);
  28618. for (i = 0; i < points.length - 1; i++) {
  28619. points[i + 1].subtractToRef(points[i], curvect);
  28620. nb = Math.floor(curvect.length() / shft);
  28621. curvect.normalize();
  28622. for (var j = 0; j < nb; j++) {
  28623. curshft = shft * j;
  28624. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28625. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28626. indices.push(idx, idx + 1);
  28627. idx += 2;
  28628. }
  28629. }
  28630. // Result
  28631. var vertexData = new VertexData();
  28632. vertexData.positions = positions;
  28633. vertexData.indices = indices;
  28634. return vertexData;
  28635. };
  28636. VertexData.CreateGround = function (options) {
  28637. var indices = [];
  28638. var positions = [];
  28639. var normals = [];
  28640. var uvs = [];
  28641. var row, col;
  28642. var width = options.width || 1;
  28643. var height = options.height || 1;
  28644. var subdivisions = options.subdivisions || 1;
  28645. for (row = 0; row <= subdivisions; row++) {
  28646. for (col = 0; col <= subdivisions; col++) {
  28647. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  28648. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28649. positions.push(position.x, position.y, position.z);
  28650. normals.push(normal.x, normal.y, normal.z);
  28651. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  28652. }
  28653. }
  28654. for (row = 0; row < subdivisions; row++) {
  28655. for (col = 0; col < subdivisions; col++) {
  28656. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28657. indices.push(col + 1 + row * (subdivisions + 1));
  28658. indices.push(col + row * (subdivisions + 1));
  28659. indices.push(col + (row + 1) * (subdivisions + 1));
  28660. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28661. indices.push(col + row * (subdivisions + 1));
  28662. }
  28663. }
  28664. // Result
  28665. var vertexData = new VertexData();
  28666. vertexData.indices = indices;
  28667. vertexData.positions = positions;
  28668. vertexData.normals = normals;
  28669. vertexData.uvs = uvs;
  28670. return vertexData;
  28671. };
  28672. VertexData.CreateTiledGround = function (options) {
  28673. var xmin = options.xmin;
  28674. var zmin = options.zmin;
  28675. var xmax = options.xmax;
  28676. var zmax = options.zmax;
  28677. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28678. var precision = options.precision || { w: 1, h: 1 };
  28679. var indices = [];
  28680. var positions = [];
  28681. var normals = [];
  28682. var uvs = [];
  28683. var row, col, tileRow, tileCol;
  28684. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  28685. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28686. precision.w = (precision.w < 1) ? 1 : precision.w;
  28687. precision.h = (precision.h < 1) ? 1 : precision.h;
  28688. var tileSize = {
  28689. 'w': (xmax - xmin) / subdivisions.w,
  28690. 'h': (zmax - zmin) / subdivisions.h
  28691. };
  28692. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28693. // Indices
  28694. var base = positions.length / 3;
  28695. var rowLength = precision.w + 1;
  28696. for (row = 0; row < precision.h; row++) {
  28697. for (col = 0; col < precision.w; col++) {
  28698. var square = [
  28699. base + col + row * rowLength,
  28700. base + (col + 1) + row * rowLength,
  28701. base + (col + 1) + (row + 1) * rowLength,
  28702. base + col + (row + 1) * rowLength
  28703. ];
  28704. indices.push(square[1]);
  28705. indices.push(square[2]);
  28706. indices.push(square[3]);
  28707. indices.push(square[0]);
  28708. indices.push(square[1]);
  28709. indices.push(square[3]);
  28710. }
  28711. }
  28712. // Position, normals and uvs
  28713. var position = BABYLON.Vector3.Zero();
  28714. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28715. for (row = 0; row <= precision.h; row++) {
  28716. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28717. for (col = 0; col <= precision.w; col++) {
  28718. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28719. position.y = 0;
  28720. positions.push(position.x, position.y, position.z);
  28721. normals.push(normal.x, normal.y, normal.z);
  28722. uvs.push(col / precision.w, row / precision.h);
  28723. }
  28724. }
  28725. }
  28726. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28727. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28728. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28729. }
  28730. }
  28731. // Result
  28732. var vertexData = new VertexData();
  28733. vertexData.indices = indices;
  28734. vertexData.positions = positions;
  28735. vertexData.normals = normals;
  28736. vertexData.uvs = uvs;
  28737. return vertexData;
  28738. };
  28739. VertexData.CreateGroundFromHeightMap = function (options) {
  28740. var indices = [];
  28741. var positions = [];
  28742. var normals = [];
  28743. var uvs = [];
  28744. var row, col;
  28745. // Vertices
  28746. for (row = 0; row <= options.subdivisions; row++) {
  28747. for (col = 0; col <= options.subdivisions; col++) {
  28748. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  28749. // Compute height
  28750. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28751. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28752. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28753. var r = options.buffer[pos] / 255.0;
  28754. var g = options.buffer[pos + 1] / 255.0;
  28755. var b = options.buffer[pos + 2] / 255.0;
  28756. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28757. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28758. // Add vertex
  28759. positions.push(position.x, position.y, position.z);
  28760. normals.push(0, 0, 0);
  28761. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28762. }
  28763. }
  28764. // Indices
  28765. for (row = 0; row < options.subdivisions; row++) {
  28766. for (col = 0; col < options.subdivisions; col++) {
  28767. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28768. indices.push(col + 1 + row * (options.subdivisions + 1));
  28769. indices.push(col + row * (options.subdivisions + 1));
  28770. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28771. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28772. indices.push(col + row * (options.subdivisions + 1));
  28773. }
  28774. }
  28775. // Normals
  28776. VertexData.ComputeNormals(positions, indices, normals);
  28777. // Result
  28778. var vertexData = new VertexData();
  28779. vertexData.indices = indices;
  28780. vertexData.positions = positions;
  28781. vertexData.normals = normals;
  28782. vertexData.uvs = uvs;
  28783. return vertexData;
  28784. };
  28785. VertexData.CreatePlane = function (options) {
  28786. var indices = [];
  28787. var positions = [];
  28788. var normals = [];
  28789. var uvs = [];
  28790. var width = options.width || options.size || 1;
  28791. var height = options.height || options.size || 1;
  28792. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28793. // Vertices
  28794. var halfWidth = width / 2.0;
  28795. var halfHeight = height / 2.0;
  28796. positions.push(-halfWidth, -halfHeight, 0);
  28797. normals.push(0, 0, -1.0);
  28798. uvs.push(0.0, 0.0);
  28799. positions.push(halfWidth, -halfHeight, 0);
  28800. normals.push(0, 0, -1.0);
  28801. uvs.push(1.0, 0.0);
  28802. positions.push(halfWidth, halfHeight, 0);
  28803. normals.push(0, 0, -1.0);
  28804. uvs.push(1.0, 1.0);
  28805. positions.push(-halfWidth, halfHeight, 0);
  28806. normals.push(0, 0, -1.0);
  28807. uvs.push(0.0, 1.0);
  28808. // Indices
  28809. indices.push(0);
  28810. indices.push(1);
  28811. indices.push(2);
  28812. indices.push(0);
  28813. indices.push(2);
  28814. indices.push(3);
  28815. // Sides
  28816. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28817. // Result
  28818. var vertexData = new VertexData();
  28819. vertexData.indices = indices;
  28820. vertexData.positions = positions;
  28821. vertexData.normals = normals;
  28822. vertexData.uvs = uvs;
  28823. return vertexData;
  28824. };
  28825. VertexData.CreateDisc = function (options) {
  28826. var positions = [];
  28827. var indices = [];
  28828. var normals = [];
  28829. var uvs = [];
  28830. var radius = options.radius || 0.5;
  28831. var tessellation = options.tessellation || 64;
  28832. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28833. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28834. // positions and uvs
  28835. positions.push(0, 0, 0); // disc center first
  28836. uvs.push(0.5, 0.5);
  28837. var theta = Math.PI * 2 * arc;
  28838. var step = theta / tessellation;
  28839. for (var a = 0; a < theta; a += step) {
  28840. var x = Math.cos(a);
  28841. var y = Math.sin(a);
  28842. var u = (x + 1) / 2;
  28843. var v = (1 - y) / 2;
  28844. positions.push(radius * x, radius * y, 0);
  28845. uvs.push(u, v);
  28846. }
  28847. if (arc === 1) {
  28848. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28849. uvs.push(uvs[2], uvs[3]);
  28850. }
  28851. //indices
  28852. var vertexNb = positions.length / 3;
  28853. for (var i = 1; i < vertexNb - 1; i++) {
  28854. indices.push(i + 1, 0, i);
  28855. }
  28856. // result
  28857. VertexData.ComputeNormals(positions, indices, normals);
  28858. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28859. var vertexData = new VertexData();
  28860. vertexData.indices = indices;
  28861. vertexData.positions = positions;
  28862. vertexData.normals = normals;
  28863. vertexData.uvs = uvs;
  28864. return vertexData;
  28865. };
  28866. VertexData.CreateIcoSphere = function (options) {
  28867. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28868. var radius = options.radius || 1;
  28869. var flat = (options.flat === undefined) ? true : options.flat;
  28870. var subdivisions = options.subdivisions || 4;
  28871. var radiusX = options.radiusX || radius;
  28872. var radiusY = options.radiusY || radius;
  28873. var radiusZ = options.radiusZ || radius;
  28874. var t = (1 + Math.sqrt(5)) / 2;
  28875. // 12 vertex x,y,z
  28876. var ico_vertices = [
  28877. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28878. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28879. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28880. ];
  28881. // index of 3 vertex makes a face of icopshere
  28882. var ico_indices = [
  28883. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28884. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28885. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28886. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28887. ];
  28888. // vertex for uv have aliased position, not for UV
  28889. var vertices_unalias_id = [
  28890. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28891. // vertex alias
  28892. 0,
  28893. 2,
  28894. 3,
  28895. 3,
  28896. 3,
  28897. 4,
  28898. 7,
  28899. 8,
  28900. 9,
  28901. 9,
  28902. 10,
  28903. 11 // 23: B + 12
  28904. ];
  28905. // uv as integer step (not pixels !)
  28906. var ico_vertexuv = [
  28907. 5, 1, 3, 1, 6, 4, 0, 0,
  28908. 5, 3, 4, 2, 2, 2, 4, 0,
  28909. 2, 0, 1, 1, 6, 0, 6, 2,
  28910. // vertex alias (for same vertex on different faces)
  28911. 0, 4,
  28912. 3, 3,
  28913. 4, 4,
  28914. 3, 1,
  28915. 4, 2,
  28916. 4, 4,
  28917. 0, 2,
  28918. 1, 1,
  28919. 2, 2,
  28920. 3, 3,
  28921. 1, 3,
  28922. 2, 4 // 23: B + 12
  28923. ];
  28924. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28925. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28926. // First island of uv mapping
  28927. // v = 4h 3+ 2
  28928. // v = 3h 9+ 4
  28929. // v = 2h 9+ 5 B
  28930. // v = 1h 9 1 0
  28931. // v = 0h 3 8 7 A
  28932. // u = 0 1 2 3 4 5 6 *a
  28933. // Second island of uv mapping
  28934. // v = 4h 0+ B+ 4+
  28935. // v = 3h A+ 2+
  28936. // v = 2h 7+ 6 3+
  28937. // v = 1h 8+ 3+
  28938. // v = 0h
  28939. // u = 0 1 2 3 4 5 6 *a
  28940. // Face layout on texture UV mapping
  28941. // ============
  28942. // \ 4 /\ 16 / ======
  28943. // \ / \ / /\ 11 /
  28944. // \/ 7 \/ / \ /
  28945. // ======= / 10 \/
  28946. // /\ 17 /\ =======
  28947. // / \ / \ \ 15 /\
  28948. // / 8 \/ 12 \ \ / \
  28949. // ============ \/ 6 \
  28950. // \ 18 /\ ============
  28951. // \ / \ \ 5 /\ 0 /
  28952. // \/ 13 \ \ / \ /
  28953. // ======= \/ 1 \/
  28954. // =============
  28955. // /\ 19 /\ 2 /\
  28956. // / \ / \ / \
  28957. // / 14 \/ 9 \/ 3 \
  28958. // ===================
  28959. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28960. var ustep = 138 / 1024;
  28961. var vstep = 239 / 1024;
  28962. var uoffset = 60 / 1024;
  28963. var voffset = 26 / 1024;
  28964. // Second island should have margin, not to touch the first island
  28965. // avoid any borderline artefact in pixel rounding
  28966. var island_u_offset = -40 / 1024;
  28967. var island_v_offset = +20 / 1024;
  28968. // face is either island 0 or 1 :
  28969. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28970. var island = [
  28971. 0, 0, 0, 0, 1,
  28972. 0, 0, 1, 1, 0,
  28973. 0, 0, 1, 1, 0,
  28974. 0, 1, 1, 1, 0 // 15 - 19
  28975. ];
  28976. var indices = [];
  28977. var positions = [];
  28978. var normals = [];
  28979. var uvs = [];
  28980. var current_indice = 0;
  28981. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28982. var face_vertex_pos = new Array(3);
  28983. var face_vertex_uv = new Array(3);
  28984. var v012;
  28985. for (v012 = 0; v012 < 3; v012++) {
  28986. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28987. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28988. }
  28989. // create all with normals
  28990. for (var face = 0; face < 20; face++) {
  28991. // 3 vertex per face
  28992. for (v012 = 0; v012 < 3; v012++) {
  28993. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28994. var v_id = ico_indices[3 * face + v012];
  28995. // vertex have 3D position (x,y,z)
  28996. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  28997. // Normalize to get normal, then scale to radius
  28998. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28999. // uv Coordinates from vertex ID
  29000. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  29001. }
  29002. // Subdivide the face (interpolate pos, norm, uv)
  29003. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29004. // - norm is linear interpolation of vertex corner normal
  29005. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29006. // - uv is linear interpolation
  29007. //
  29008. // Topology is as below for sub-divide by 2
  29009. // vertex shown as v0,v1,v2
  29010. // interp index is i1 to progress in range [v0,v1[
  29011. // interp index is i2 to progress in range [v0,v2[
  29012. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29013. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29014. //
  29015. //
  29016. // i2 v2
  29017. // ^ ^
  29018. // / / \
  29019. // / / \
  29020. // / / \
  29021. // / / (0,1) \
  29022. // / #---------\
  29023. // / / \ (0,0)'/ \
  29024. // / / \ / \
  29025. // / / \ / \
  29026. // / / (0,0) \ / (1,0) \
  29027. // / #---------#---------\
  29028. // v0 v1
  29029. //
  29030. // --------------------> i1
  29031. //
  29032. // interp of (i1,i2):
  29033. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29034. // along i1 : lerp(x0,x1, i1/(S-i2))
  29035. //
  29036. // centroid of triangle is needed to get help normal computation
  29037. // (c1,c2) are used for centroid location
  29038. var interp_vertex = function (i1, i2, c1, c2) {
  29039. // vertex is interpolated from
  29040. // - face_vertex_pos[0..2]
  29041. // - face_vertex_uv[0..2]
  29042. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29043. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29044. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29045. pos_interp.normalize();
  29046. var vertex_normal;
  29047. if (flat) {
  29048. // in flat mode, recalculate normal as face centroid normal
  29049. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29050. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29051. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29052. }
  29053. else {
  29054. // in smooth mode, recalculate normal from each single vertex position
  29055. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29056. }
  29057. // Vertex normal need correction due to X,Y,Z radius scaling
  29058. vertex_normal.x /= radiusX;
  29059. vertex_normal.y /= radiusY;
  29060. vertex_normal.z /= radiusZ;
  29061. vertex_normal.normalize();
  29062. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29063. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29064. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29065. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29066. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29067. uvs.push(uv_interp.x, uv_interp.y);
  29068. // push each vertex has member of a face
  29069. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29070. indices.push(current_indice);
  29071. current_indice++;
  29072. };
  29073. for (var i2 = 0; i2 < subdivisions; i2++) {
  29074. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29075. // face : (i1,i2) for /\ :
  29076. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29077. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29078. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29079. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29080. if (i1 + i2 + 1 < subdivisions) {
  29081. // face : (i1,i2)' for \/ :
  29082. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29083. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29084. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29085. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29086. }
  29087. }
  29088. }
  29089. }
  29090. // Sides
  29091. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29092. // Result
  29093. var vertexData = new VertexData();
  29094. vertexData.indices = indices;
  29095. vertexData.positions = positions;
  29096. vertexData.normals = normals;
  29097. vertexData.uvs = uvs;
  29098. return vertexData;
  29099. };
  29100. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29101. VertexData.CreatePolyhedron = function (options) {
  29102. // provided polyhedron types :
  29103. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29104. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  29105. var polyhedra = [];
  29106. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  29107. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  29108. polyhedra[2] = {
  29109. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  29110. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  29111. };
  29112. polyhedra[3] = {
  29113. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  29114. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  29115. };
  29116. polyhedra[4] = {
  29117. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  29118. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  29119. };
  29120. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  29121. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  29122. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  29123. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  29124. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  29125. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  29126. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  29127. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  29128. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  29129. polyhedra[14] = {
  29130. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  29131. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  29132. };
  29133. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29134. var size = options.size;
  29135. var sizeX = options.sizeX || size || 1;
  29136. var sizeY = options.sizeY || size || 1;
  29137. var sizeZ = options.sizeZ || size || 1;
  29138. var data = options.custom || polyhedra[type];
  29139. var nbfaces = data.face.length;
  29140. var faceUV = options.faceUV || new Array(nbfaces);
  29141. var faceColors = options.faceColors;
  29142. var flat = (options.flat === undefined) ? true : options.flat;
  29143. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29144. var positions = [];
  29145. var indices = [];
  29146. var normals = [];
  29147. var uvs = [];
  29148. var colors = [];
  29149. var index = 0;
  29150. var faceIdx = 0; // face cursor in the array "indexes"
  29151. var indexes = [];
  29152. var i = 0;
  29153. var f = 0;
  29154. var u, v, ang, x, y, tmp;
  29155. // default face colors and UV if undefined
  29156. if (flat) {
  29157. for (f = 0; f < nbfaces; f++) {
  29158. if (faceColors && faceColors[f] === undefined) {
  29159. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29160. }
  29161. if (faceUV && faceUV[f] === undefined) {
  29162. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29163. }
  29164. }
  29165. }
  29166. if (!flat) {
  29167. for (i = 0; i < data.vertex.length; i++) {
  29168. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29169. uvs.push(0, 0);
  29170. }
  29171. for (f = 0; f < nbfaces; f++) {
  29172. for (i = 0; i < data.face[f].length - 2; i++) {
  29173. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29174. }
  29175. }
  29176. }
  29177. else {
  29178. for (f = 0; f < nbfaces; f++) {
  29179. var fl = data.face[f].length; // number of vertices of the current face
  29180. ang = 2 * Math.PI / fl;
  29181. x = 0.5 * Math.tan(ang / 2);
  29182. y = 0.5;
  29183. // positions, uvs, colors
  29184. for (i = 0; i < fl; i++) {
  29185. // positions
  29186. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  29187. indexes.push(index);
  29188. index++;
  29189. // uvs
  29190. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29191. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29192. uvs.push(u, v);
  29193. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29194. y = x * Math.sin(ang) + y * Math.cos(ang);
  29195. x = tmp;
  29196. // colors
  29197. if (faceColors) {
  29198. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29199. }
  29200. }
  29201. // indices from indexes
  29202. for (i = 0; i < fl - 2; i++) {
  29203. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29204. }
  29205. faceIdx += fl;
  29206. }
  29207. }
  29208. VertexData.ComputeNormals(positions, indices, normals);
  29209. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29210. var vertexData = new VertexData();
  29211. vertexData.positions = positions;
  29212. vertexData.indices = indices;
  29213. vertexData.normals = normals;
  29214. vertexData.uvs = uvs;
  29215. if (faceColors && flat) {
  29216. vertexData.colors = colors;
  29217. }
  29218. return vertexData;
  29219. };
  29220. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29221. VertexData.CreateTorusKnot = function (options) {
  29222. var indices = [];
  29223. var positions = [];
  29224. var normals = [];
  29225. var uvs = [];
  29226. var radius = options.radius || 2;
  29227. var tube = options.tube || 0.5;
  29228. var radialSegments = options.radialSegments || 32;
  29229. var tubularSegments = options.tubularSegments || 32;
  29230. var p = options.p || 2;
  29231. var q = options.q || 3;
  29232. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29233. // Helper
  29234. var getPos = function (angle) {
  29235. var cu = Math.cos(angle);
  29236. var su = Math.sin(angle);
  29237. var quOverP = q / p * angle;
  29238. var cs = Math.cos(quOverP);
  29239. var tx = radius * (2 + cs) * 0.5 * cu;
  29240. var ty = radius * (2 + cs) * su * 0.5;
  29241. var tz = radius * Math.sin(quOverP) * 0.5;
  29242. return new BABYLON.Vector3(tx, ty, tz);
  29243. };
  29244. // Vertices
  29245. var i;
  29246. var j;
  29247. for (i = 0; i <= radialSegments; i++) {
  29248. var modI = i % radialSegments;
  29249. var u = modI / radialSegments * 2 * p * Math.PI;
  29250. var p1 = getPos(u);
  29251. var p2 = getPos(u + 0.01);
  29252. var tang = p2.subtract(p1);
  29253. var n = p2.add(p1);
  29254. var bitan = BABYLON.Vector3.Cross(tang, n);
  29255. n = BABYLON.Vector3.Cross(bitan, tang);
  29256. bitan.normalize();
  29257. n.normalize();
  29258. for (j = 0; j < tubularSegments; j++) {
  29259. var modJ = j % tubularSegments;
  29260. var v = modJ / tubularSegments * 2 * Math.PI;
  29261. var cx = -tube * Math.cos(v);
  29262. var cy = tube * Math.sin(v);
  29263. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29264. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29265. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29266. uvs.push(i / radialSegments);
  29267. uvs.push(j / tubularSegments);
  29268. }
  29269. }
  29270. for (i = 0; i < radialSegments; i++) {
  29271. for (j = 0; j < tubularSegments; j++) {
  29272. var jNext = (j + 1) % tubularSegments;
  29273. var a = i * tubularSegments + j;
  29274. var b = (i + 1) * tubularSegments + j;
  29275. var c = (i + 1) * tubularSegments + jNext;
  29276. var d = i * tubularSegments + jNext;
  29277. indices.push(d);
  29278. indices.push(b);
  29279. indices.push(a);
  29280. indices.push(d);
  29281. indices.push(c);
  29282. indices.push(b);
  29283. }
  29284. }
  29285. // Normals
  29286. VertexData.ComputeNormals(positions, indices, normals);
  29287. // Sides
  29288. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29289. // Result
  29290. var vertexData = new VertexData();
  29291. vertexData.indices = indices;
  29292. vertexData.positions = positions;
  29293. vertexData.normals = normals;
  29294. vertexData.uvs = uvs;
  29295. return vertexData;
  29296. };
  29297. // Tools
  29298. /**
  29299. * @param {any} - positions (number[] or Float32Array)
  29300. * @param {any} - indices (number[] or Uint16Array)
  29301. * @param {any} - normals (number[] or Float32Array)
  29302. */
  29303. VertexData.ComputeNormals = function (positions, indices, normals) {
  29304. var index = 0;
  29305. var p1p2x = 0.0;
  29306. var p1p2y = 0.0;
  29307. var p1p2z = 0.0;
  29308. var p3p2x = 0.0;
  29309. var p3p2y = 0.0;
  29310. var p3p2z = 0.0;
  29311. var faceNormalx = 0.0;
  29312. var faceNormaly = 0.0;
  29313. var faceNormalz = 0.0;
  29314. var length = 0.0;
  29315. var i1 = 0;
  29316. var i2 = 0;
  29317. var i3 = 0;
  29318. for (index = 0; index < positions.length; index++) {
  29319. normals[index] = 0.0;
  29320. }
  29321. // indice triplet = 1 face
  29322. var nbFaces = indices.length / 3;
  29323. for (index = 0; index < nbFaces; index++) {
  29324. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  29325. i2 = indices[index * 3 + 1];
  29326. i3 = indices[index * 3 + 2];
  29327. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  29328. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  29329. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  29330. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  29331. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  29332. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  29333. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  29334. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  29335. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  29336. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29337. length = (length === 0) ? 1.0 : length;
  29338. faceNormalx /= length; // normalize this normal
  29339. faceNormaly /= length;
  29340. faceNormalz /= length;
  29341. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  29342. normals[i1 * 3 + 1] += faceNormaly;
  29343. normals[i1 * 3 + 2] += faceNormalz;
  29344. normals[i2 * 3] += faceNormalx;
  29345. normals[i2 * 3 + 1] += faceNormaly;
  29346. normals[i2 * 3 + 2] += faceNormalz;
  29347. normals[i3 * 3] += faceNormalx;
  29348. normals[i3 * 3 + 1] += faceNormaly;
  29349. normals[i3 * 3 + 2] += faceNormalz;
  29350. }
  29351. // last normalization of each normal
  29352. for (index = 0; index < normals.length / 3; index++) {
  29353. faceNormalx = normals[index * 3];
  29354. faceNormaly = normals[index * 3 + 1];
  29355. faceNormalz = normals[index * 3 + 2];
  29356. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29357. length = (length === 0) ? 1.0 : length;
  29358. faceNormalx /= length;
  29359. faceNormaly /= length;
  29360. faceNormalz /= length;
  29361. normals[index * 3] = faceNormalx;
  29362. normals[index * 3 + 1] = faceNormaly;
  29363. normals[index * 3 + 2] = faceNormalz;
  29364. }
  29365. };
  29366. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  29367. var li = indices.length;
  29368. var ln = normals.length;
  29369. var i;
  29370. var n;
  29371. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29372. switch (sideOrientation) {
  29373. case BABYLON.Mesh.FRONTSIDE:
  29374. // nothing changed
  29375. break;
  29376. case BABYLON.Mesh.BACKSIDE:
  29377. var tmp;
  29378. // indices
  29379. for (i = 0; i < li; i += 3) {
  29380. tmp = indices[i];
  29381. indices[i] = indices[i + 2];
  29382. indices[i + 2] = tmp;
  29383. }
  29384. // normals
  29385. for (n = 0; n < ln; n++) {
  29386. normals[n] = -normals[n];
  29387. }
  29388. break;
  29389. case BABYLON.Mesh.DOUBLESIDE:
  29390. // positions
  29391. var lp = positions.length;
  29392. var l = lp / 3;
  29393. for (var p = 0; p < lp; p++) {
  29394. positions[lp + p] = positions[p];
  29395. }
  29396. // indices
  29397. for (i = 0; i < li; i += 3) {
  29398. indices[i + li] = indices[i + 2] + l;
  29399. indices[i + 1 + li] = indices[i + 1] + l;
  29400. indices[i + 2 + li] = indices[i] + l;
  29401. }
  29402. // normals
  29403. for (n = 0; n < ln; n++) {
  29404. normals[ln + n] = -normals[n];
  29405. }
  29406. // uvs
  29407. var lu = uvs.length;
  29408. for (var u = 0; u < lu; u++) {
  29409. uvs[u + lu] = uvs[u];
  29410. }
  29411. break;
  29412. }
  29413. };
  29414. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29415. var vertexData = new VertexData();
  29416. // positions
  29417. var positions = parsedVertexData.positions;
  29418. if (positions) {
  29419. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29420. }
  29421. // normals
  29422. var normals = parsedVertexData.normals;
  29423. if (normals) {
  29424. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29425. }
  29426. // uvs
  29427. var uvs = parsedVertexData.uvs;
  29428. if (uvs) {
  29429. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29430. }
  29431. // uv2s
  29432. var uv2s = parsedVertexData.uv2s;
  29433. if (uv2s) {
  29434. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29435. }
  29436. // uv3s
  29437. var uv3s = parsedVertexData.uv3s;
  29438. if (uv3s) {
  29439. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29440. }
  29441. // uv4s
  29442. var uv4s = parsedVertexData.uv4s;
  29443. if (uv4s) {
  29444. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29445. }
  29446. // uv5s
  29447. var uv5s = parsedVertexData.uv5s;
  29448. if (uv5s) {
  29449. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29450. }
  29451. // uv6s
  29452. var uv6s = parsedVertexData.uv6s;
  29453. if (uv6s) {
  29454. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29455. }
  29456. // colors
  29457. var colors = parsedVertexData.colors;
  29458. if (colors) {
  29459. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29460. }
  29461. // matricesIndices
  29462. var matricesIndices = parsedVertexData.matricesIndices;
  29463. if (matricesIndices) {
  29464. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29465. }
  29466. // matricesWeights
  29467. var matricesWeights = parsedVertexData.matricesWeights;
  29468. if (matricesWeights) {
  29469. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29470. }
  29471. // indices
  29472. var indices = parsedVertexData.indices;
  29473. if (indices) {
  29474. vertexData.indices = indices;
  29475. }
  29476. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29477. };
  29478. return VertexData;
  29479. })();
  29480. BABYLON.VertexData = VertexData;
  29481. })(BABYLON || (BABYLON = {}));
  29482. var BABYLON;
  29483. (function (BABYLON) {
  29484. var Tags = (function () {
  29485. function Tags() {
  29486. }
  29487. Tags.EnableFor = function (obj) {
  29488. obj._tags = obj._tags || {};
  29489. obj.hasTags = function () {
  29490. return Tags.HasTags(obj);
  29491. };
  29492. obj.addTags = function (tagsString) {
  29493. return Tags.AddTagsTo(obj, tagsString);
  29494. };
  29495. obj.removeTags = function (tagsString) {
  29496. return Tags.RemoveTagsFrom(obj, tagsString);
  29497. };
  29498. obj.matchesTagsQuery = function (tagsQuery) {
  29499. return Tags.MatchesQuery(obj, tagsQuery);
  29500. };
  29501. };
  29502. Tags.DisableFor = function (obj) {
  29503. delete obj._tags;
  29504. delete obj.hasTags;
  29505. delete obj.addTags;
  29506. delete obj.removeTags;
  29507. delete obj.matchesTagsQuery;
  29508. };
  29509. Tags.HasTags = function (obj) {
  29510. if (!obj._tags) {
  29511. return false;
  29512. }
  29513. return !BABYLON.Tools.IsEmpty(obj._tags);
  29514. };
  29515. Tags.GetTags = function (obj, asString) {
  29516. if (asString === void 0) { asString = true; }
  29517. if (!obj._tags) {
  29518. return null;
  29519. }
  29520. if (asString) {
  29521. var tagsArray = [];
  29522. for (var tag in obj._tags) {
  29523. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  29524. tagsArray.push(tag);
  29525. }
  29526. }
  29527. return tagsArray.join(" ");
  29528. }
  29529. else {
  29530. return obj._tags;
  29531. }
  29532. };
  29533. // the tags 'true' and 'false' are reserved and cannot be used as tags
  29534. // a tag cannot start with '||', '&&', and '!'
  29535. // it cannot contain whitespaces
  29536. Tags.AddTagsTo = function (obj, tagsString) {
  29537. if (!tagsString) {
  29538. return;
  29539. }
  29540. if (typeof tagsString !== "string") {
  29541. return;
  29542. }
  29543. var tags = tagsString.split(" ");
  29544. for (var t in tags) {
  29545. Tags._AddTagTo(obj, tags[t]);
  29546. }
  29547. };
  29548. Tags._AddTagTo = function (obj, tag) {
  29549. tag = tag.trim();
  29550. if (tag === "" || tag === "true" || tag === "false") {
  29551. return;
  29552. }
  29553. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  29554. return;
  29555. }
  29556. Tags.EnableFor(obj);
  29557. obj._tags[tag] = true;
  29558. };
  29559. Tags.RemoveTagsFrom = function (obj, tagsString) {
  29560. if (!Tags.HasTags(obj)) {
  29561. return;
  29562. }
  29563. var tags = tagsString.split(" ");
  29564. for (var t in tags) {
  29565. Tags._RemoveTagFrom(obj, tags[t]);
  29566. }
  29567. };
  29568. Tags._RemoveTagFrom = function (obj, tag) {
  29569. delete obj._tags[tag];
  29570. };
  29571. Tags.MatchesQuery = function (obj, tagsQuery) {
  29572. if (tagsQuery === undefined) {
  29573. return true;
  29574. }
  29575. if (tagsQuery === "") {
  29576. return Tags.HasTags(obj);
  29577. }
  29578. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  29579. };
  29580. return Tags;
  29581. })();
  29582. BABYLON.Tags = Tags;
  29583. })(BABYLON || (BABYLON = {}));
  29584. var BABYLON;
  29585. (function (BABYLON) {
  29586. var Internals;
  29587. (function (Internals) {
  29588. var AndOrNotEvaluator = (function () {
  29589. function AndOrNotEvaluator() {
  29590. }
  29591. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  29592. if (!query.match(/\([^\(\)]*\)/g)) {
  29593. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  29594. }
  29595. else {
  29596. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  29597. // remove parenthesis
  29598. r = r.slice(1, r.length - 1);
  29599. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  29600. });
  29601. }
  29602. if (query === "true") {
  29603. return true;
  29604. }
  29605. if (query === "false") {
  29606. return false;
  29607. }
  29608. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  29609. };
  29610. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  29611. evaluateCallback = evaluateCallback || (function (r) {
  29612. return r === "true" ? true : false;
  29613. });
  29614. var result;
  29615. var or = parenthesisContent.split("||");
  29616. for (var i in or) {
  29617. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  29618. var and = ori.split("&&");
  29619. if (and.length > 1) {
  29620. for (var j = 0; j < and.length; ++j) {
  29621. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  29622. if (andj !== "true" && andj !== "false") {
  29623. if (andj[0] === "!") {
  29624. result = !evaluateCallback(andj.substring(1));
  29625. }
  29626. else {
  29627. result = evaluateCallback(andj);
  29628. }
  29629. }
  29630. else {
  29631. result = andj === "true" ? true : false;
  29632. }
  29633. if (!result) {
  29634. ori = "false";
  29635. break;
  29636. }
  29637. }
  29638. }
  29639. if (result || ori === "true") {
  29640. result = true;
  29641. break;
  29642. }
  29643. // result equals false (or undefined)
  29644. if (ori !== "true" && ori !== "false") {
  29645. if (ori[0] === "!") {
  29646. result = !evaluateCallback(ori.substring(1));
  29647. }
  29648. else {
  29649. result = evaluateCallback(ori);
  29650. }
  29651. }
  29652. else {
  29653. result = ori === "true" ? true : false;
  29654. }
  29655. }
  29656. // the whole parenthesis scope is replaced by 'true' or 'false'
  29657. return result ? "true" : "false";
  29658. };
  29659. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  29660. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  29661. // remove whitespaces
  29662. r = r.replace(/[\s]/g, function () { return ""; });
  29663. return r.length % 2 ? "!" : "";
  29664. });
  29665. booleanString = booleanString.trim();
  29666. if (booleanString === "!true") {
  29667. booleanString = "false";
  29668. }
  29669. else if (booleanString === "!false") {
  29670. booleanString = "true";
  29671. }
  29672. return booleanString;
  29673. };
  29674. return AndOrNotEvaluator;
  29675. })();
  29676. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  29677. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29678. })(BABYLON || (BABYLON = {}));
  29679. var BABYLON;
  29680. (function (BABYLON) {
  29681. var PostProcessRenderPass = (function () {
  29682. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  29683. this._enabled = true;
  29684. this._refCount = 0;
  29685. this._name = name;
  29686. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  29687. this.setRenderList(renderList);
  29688. this._renderTexture.onBeforeRender = beforeRender;
  29689. this._renderTexture.onAfterRender = afterRender;
  29690. this._scene = scene;
  29691. this._renderList = renderList;
  29692. }
  29693. // private
  29694. PostProcessRenderPass.prototype._incRefCount = function () {
  29695. if (this._refCount === 0) {
  29696. this._scene.customRenderTargets.push(this._renderTexture);
  29697. }
  29698. return ++this._refCount;
  29699. };
  29700. PostProcessRenderPass.prototype._decRefCount = function () {
  29701. this._refCount--;
  29702. if (this._refCount <= 0) {
  29703. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  29704. }
  29705. return this._refCount;
  29706. };
  29707. PostProcessRenderPass.prototype._update = function () {
  29708. this.setRenderList(this._renderList);
  29709. };
  29710. // public
  29711. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  29712. this._renderTexture.renderList = renderList;
  29713. };
  29714. PostProcessRenderPass.prototype.getRenderTexture = function () {
  29715. return this._renderTexture;
  29716. };
  29717. return PostProcessRenderPass;
  29718. })();
  29719. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  29720. })(BABYLON || (BABYLON = {}));
  29721. var BABYLON;
  29722. (function (BABYLON) {
  29723. var PostProcessRenderEffect = (function () {
  29724. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  29725. this._engine = engine;
  29726. this._name = name;
  29727. this._singleInstance = singleInstance || true;
  29728. this._getPostProcess = getPostProcess;
  29729. this._cameras = [];
  29730. this._indicesForCamera = [];
  29731. this._postProcesses = {};
  29732. this._renderPasses = {};
  29733. this._renderEffectAsPasses = {};
  29734. }
  29735. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  29736. get: function () {
  29737. for (var index in this._postProcesses) {
  29738. if (!this._postProcesses[index].isSupported) {
  29739. return false;
  29740. }
  29741. }
  29742. return true;
  29743. },
  29744. enumerable: true,
  29745. configurable: true
  29746. });
  29747. PostProcessRenderEffect.prototype._update = function () {
  29748. for (var renderPassName in this._renderPasses) {
  29749. this._renderPasses[renderPassName]._update();
  29750. }
  29751. };
  29752. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  29753. this._renderPasses[renderPass._name] = renderPass;
  29754. this._linkParameters();
  29755. };
  29756. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  29757. delete this._renderPasses[renderPass._name];
  29758. this._linkParameters();
  29759. };
  29760. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  29761. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  29762. this._linkParameters();
  29763. };
  29764. PostProcessRenderEffect.prototype.getPass = function (passName) {
  29765. for (var renderPassName in this._renderPasses) {
  29766. if (renderPassName === passName) {
  29767. return this._renderPasses[passName];
  29768. }
  29769. }
  29770. };
  29771. PostProcessRenderEffect.prototype.emptyPasses = function () {
  29772. this._renderPasses = {};
  29773. this._linkParameters();
  29774. };
  29775. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  29776. var cameraKey;
  29777. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29778. for (var i = 0; i < _cam.length; i++) {
  29779. var camera = _cam[i];
  29780. var cameraName = camera.name;
  29781. if (this._singleInstance) {
  29782. cameraKey = 0;
  29783. }
  29784. else {
  29785. cameraKey = cameraName;
  29786. }
  29787. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  29788. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  29789. if (!this._indicesForCamera[cameraName]) {
  29790. this._indicesForCamera[cameraName] = [];
  29791. }
  29792. this._indicesForCamera[cameraName].push(index);
  29793. if (this._cameras.indexOf(camera) === -1) {
  29794. this._cameras[cameraName] = camera;
  29795. }
  29796. for (var passName in this._renderPasses) {
  29797. this._renderPasses[passName]._incRefCount();
  29798. }
  29799. }
  29800. this._linkParameters();
  29801. };
  29802. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  29803. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29804. for (var i = 0; i < _cam.length; i++) {
  29805. var camera = _cam[i];
  29806. var cameraName = camera.name;
  29807. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29808. var index = this._cameras.indexOf(cameraName);
  29809. this._indicesForCamera.splice(index, 1);
  29810. this._cameras.splice(index, 1);
  29811. for (var passName in this._renderPasses) {
  29812. this._renderPasses[passName]._decRefCount();
  29813. }
  29814. }
  29815. };
  29816. PostProcessRenderEffect.prototype._enable = function (cameras) {
  29817. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29818. for (var i = 0; i < _cam.length; i++) {
  29819. var camera = _cam[i];
  29820. var cameraName = camera.name;
  29821. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  29822. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  29823. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  29824. }
  29825. }
  29826. for (var passName in this._renderPasses) {
  29827. this._renderPasses[passName]._incRefCount();
  29828. }
  29829. }
  29830. };
  29831. PostProcessRenderEffect.prototype._disable = function (cameras) {
  29832. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29833. for (var i = 0; i < _cam.length; i++) {
  29834. var camera = _cam[i];
  29835. var cameraName = camera.Name;
  29836. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29837. for (var passName in this._renderPasses) {
  29838. this._renderPasses[passName]._decRefCount();
  29839. }
  29840. }
  29841. };
  29842. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  29843. if (this._singleInstance) {
  29844. return this._postProcesses[0];
  29845. }
  29846. else {
  29847. return this._postProcesses[camera.name];
  29848. }
  29849. };
  29850. PostProcessRenderEffect.prototype._linkParameters = function () {
  29851. var _this = this;
  29852. for (var index in this._postProcesses) {
  29853. if (this.applyParameters) {
  29854. this.applyParameters(this._postProcesses[index]);
  29855. }
  29856. this._postProcesses[index].onBeforeRender = function (effect) {
  29857. _this._linkTextures(effect);
  29858. };
  29859. }
  29860. };
  29861. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  29862. for (var renderPassName in this._renderPasses) {
  29863. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  29864. }
  29865. for (var renderEffectName in this._renderEffectAsPasses) {
  29866. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  29867. }
  29868. };
  29869. return PostProcessRenderEffect;
  29870. })();
  29871. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  29872. })(BABYLON || (BABYLON = {}));
  29873. var BABYLON;
  29874. (function (BABYLON) {
  29875. var PostProcessRenderPipeline = (function () {
  29876. function PostProcessRenderPipeline(engine, name) {
  29877. this._engine = engine;
  29878. this._name = name;
  29879. this._renderEffects = {};
  29880. this._renderEffectsForIsolatedPass = {};
  29881. this._cameras = [];
  29882. }
  29883. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  29884. get: function () {
  29885. for (var renderEffectName in this._renderEffects) {
  29886. if (!this._renderEffects[renderEffectName].isSupported) {
  29887. return false;
  29888. }
  29889. }
  29890. return true;
  29891. },
  29892. enumerable: true,
  29893. configurable: true
  29894. });
  29895. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  29896. this._renderEffects[renderEffect._name] = renderEffect;
  29897. };
  29898. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  29899. var renderEffects = this._renderEffects[renderEffectName];
  29900. if (!renderEffects) {
  29901. return;
  29902. }
  29903. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29904. };
  29905. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  29906. var renderEffects = this._renderEffects[renderEffectName];
  29907. if (!renderEffects) {
  29908. return;
  29909. }
  29910. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29911. };
  29912. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  29913. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29914. var indicesToDelete = [];
  29915. var i;
  29916. for (i = 0; i < _cam.length; i++) {
  29917. var camera = _cam[i];
  29918. var cameraName = camera.name;
  29919. if (this._cameras.indexOf(camera) === -1) {
  29920. this._cameras[cameraName] = camera;
  29921. }
  29922. else if (unique) {
  29923. indicesToDelete.push(i);
  29924. }
  29925. }
  29926. for (i = 0; i < indicesToDelete.length; i++) {
  29927. cameras.splice(indicesToDelete[i], 1);
  29928. }
  29929. for (var renderEffectName in this._renderEffects) {
  29930. this._renderEffects[renderEffectName]._attachCameras(_cam);
  29931. }
  29932. };
  29933. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  29934. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29935. for (var renderEffectName in this._renderEffects) {
  29936. this._renderEffects[renderEffectName]._detachCameras(_cam);
  29937. }
  29938. for (var i = 0; i < _cam.length; i++) {
  29939. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  29940. }
  29941. };
  29942. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  29943. var _this = this;
  29944. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29945. var pass = null;
  29946. var renderEffectName;
  29947. for (renderEffectName in this._renderEffects) {
  29948. pass = this._renderEffects[renderEffectName].getPass(passName);
  29949. if (pass != null) {
  29950. break;
  29951. }
  29952. }
  29953. if (pass === null) {
  29954. return;
  29955. }
  29956. for (renderEffectName in this._renderEffects) {
  29957. this._renderEffects[renderEffectName]._disable(_cam);
  29958. }
  29959. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  29960. for (var i = 0; i < _cam.length; i++) {
  29961. var camera = _cam[i];
  29962. var cameraName = camera.name;
  29963. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  29964. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  29965. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  29966. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  29967. }
  29968. };
  29969. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  29970. var _this = this;
  29971. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29972. for (var i = 0; i < _cam.length; i++) {
  29973. var camera = _cam[i];
  29974. var cameraName = camera.name;
  29975. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  29976. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  29977. }
  29978. for (var renderEffectName in this._renderEffects) {
  29979. this._renderEffects[renderEffectName]._enable(_cam);
  29980. }
  29981. };
  29982. PostProcessRenderPipeline.prototype._update = function () {
  29983. for (var renderEffectName in this._renderEffects) {
  29984. this._renderEffects[renderEffectName]._update();
  29985. }
  29986. for (var i = 0; i < this._cameras.length; i++) {
  29987. var cameraName = this._cameras[i].name;
  29988. if (this._renderEffectsForIsolatedPass[cameraName]) {
  29989. this._renderEffectsForIsolatedPass[cameraName]._update();
  29990. }
  29991. }
  29992. };
  29993. PostProcessRenderPipeline.prototype.dispose = function () {
  29994. // Must be implemented by children
  29995. };
  29996. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  29997. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  29998. return PostProcessRenderPipeline;
  29999. })();
  30000. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  30001. })(BABYLON || (BABYLON = {}));
  30002. var BABYLON;
  30003. (function (BABYLON) {
  30004. var PostProcessRenderPipelineManager = (function () {
  30005. function PostProcessRenderPipelineManager() {
  30006. this._renderPipelines = {};
  30007. }
  30008. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  30009. this._renderPipelines[renderPipeline._name] = renderPipeline;
  30010. };
  30011. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  30012. var renderPipeline = this._renderPipelines[renderPipelineName];
  30013. if (!renderPipeline) {
  30014. return;
  30015. }
  30016. renderPipeline._attachCameras(cameras, unique);
  30017. };
  30018. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  30019. var renderPipeline = this._renderPipelines[renderPipelineName];
  30020. if (!renderPipeline) {
  30021. return;
  30022. }
  30023. renderPipeline._detachCameras(cameras);
  30024. };
  30025. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30026. var renderPipeline = this._renderPipelines[renderPipelineName];
  30027. if (!renderPipeline) {
  30028. return;
  30029. }
  30030. renderPipeline._enableEffect(renderEffectName, cameras);
  30031. };
  30032. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30033. var renderPipeline = this._renderPipelines[renderPipelineName];
  30034. if (!renderPipeline) {
  30035. return;
  30036. }
  30037. renderPipeline._disableEffect(renderEffectName, cameras);
  30038. };
  30039. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  30040. var renderPipeline = this._renderPipelines[renderPipelineName];
  30041. if (!renderPipeline) {
  30042. return;
  30043. }
  30044. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  30045. };
  30046. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  30047. var renderPipeline = this._renderPipelines[renderPipelineName];
  30048. if (!renderPipeline) {
  30049. return;
  30050. }
  30051. renderPipeline._disableDisplayOnlyPass(cameras);
  30052. };
  30053. PostProcessRenderPipelineManager.prototype.update = function () {
  30054. for (var renderPipelineName in this._renderPipelines) {
  30055. var pipeline = this._renderPipelines[renderPipelineName];
  30056. if (!pipeline.isSupported) {
  30057. pipeline.dispose();
  30058. delete this._renderPipelines[renderPipelineName];
  30059. }
  30060. else {
  30061. pipeline._update();
  30062. }
  30063. }
  30064. };
  30065. return PostProcessRenderPipelineManager;
  30066. })();
  30067. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  30068. })(BABYLON || (BABYLON = {}));
  30069. var BABYLON;
  30070. (function (BABYLON) {
  30071. var BoundingBoxRenderer = (function () {
  30072. function BoundingBoxRenderer(scene) {
  30073. this.frontColor = new BABYLON.Color3(1, 1, 1);
  30074. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  30075. this.showBackLines = true;
  30076. this.renderList = new BABYLON.SmartArray(32);
  30077. this._scene = scene;
  30078. }
  30079. BoundingBoxRenderer.prototype._prepareRessources = function () {
  30080. if (this._colorShader) {
  30081. return;
  30082. }
  30083. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  30084. attributes: ["position"],
  30085. uniforms: ["worldViewProjection", "color"]
  30086. });
  30087. var engine = this._scene.getEngine();
  30088. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  30089. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  30090. this._ib = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  30091. };
  30092. BoundingBoxRenderer.prototype.reset = function () {
  30093. this.renderList.reset();
  30094. };
  30095. BoundingBoxRenderer.prototype.render = function () {
  30096. if (this.renderList.length === 0) {
  30097. return;
  30098. }
  30099. this._prepareRessources();
  30100. if (!this._colorShader.isReady()) {
  30101. return;
  30102. }
  30103. var engine = this._scene.getEngine();
  30104. engine.setDepthWrite(false);
  30105. this._colorShader._preBind();
  30106. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  30107. var boundingBox = this.renderList.data[boundingBoxIndex];
  30108. var min = boundingBox.minimum;
  30109. var max = boundingBox.maximum;
  30110. var diff = max.subtract(min);
  30111. var median = min.add(diff.scale(0.5));
  30112. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  30113. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  30114. .multiply(boundingBox.getWorldMatrix());
  30115. // VBOs
  30116. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  30117. if (this.showBackLines) {
  30118. // Back
  30119. engine.setDepthFunctionToGreaterOrEqual();
  30120. this._scene.resetCachedMaterial();
  30121. this._colorShader.setColor4("color", this.backColor.toColor4());
  30122. this._colorShader.bind(worldMatrix);
  30123. // Draw order
  30124. engine.draw(false, 0, 24);
  30125. }
  30126. // Front
  30127. engine.setDepthFunctionToLess();
  30128. this._scene.resetCachedMaterial();
  30129. this._colorShader.setColor4("color", this.frontColor.toColor4());
  30130. this._colorShader.bind(worldMatrix);
  30131. // Draw order
  30132. engine.draw(false, 0, 24);
  30133. }
  30134. this._colorShader.unbind();
  30135. engine.setDepthFunctionToLessOrEqual();
  30136. engine.setDepthWrite(true);
  30137. };
  30138. BoundingBoxRenderer.prototype.dispose = function () {
  30139. if (!this._colorShader) {
  30140. return;
  30141. }
  30142. this._colorShader.dispose();
  30143. this._vb.dispose();
  30144. this._scene.getEngine()._releaseBuffer(this._ib);
  30145. };
  30146. return BoundingBoxRenderer;
  30147. })();
  30148. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  30149. })(BABYLON || (BABYLON = {}));
  30150. var BABYLON;
  30151. (function (BABYLON) {
  30152. var Condition = (function () {
  30153. function Condition(actionManager) {
  30154. this._actionManager = actionManager;
  30155. }
  30156. Condition.prototype.isValid = function () {
  30157. return true;
  30158. };
  30159. Condition.prototype._getProperty = function (propertyPath) {
  30160. return this._actionManager._getProperty(propertyPath);
  30161. };
  30162. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  30163. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30164. };
  30165. Condition.prototype.serialize = function () {
  30166. };
  30167. Condition.prototype._serialize = function (serializedCondition) {
  30168. return {
  30169. type: 2,
  30170. children: [],
  30171. name: serializedCondition.name,
  30172. properties: serializedCondition.properties
  30173. };
  30174. };
  30175. return Condition;
  30176. })();
  30177. BABYLON.Condition = Condition;
  30178. var ValueCondition = (function (_super) {
  30179. __extends(ValueCondition, _super);
  30180. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  30181. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  30182. _super.call(this, actionManager);
  30183. this.propertyPath = propertyPath;
  30184. this.value = value;
  30185. this.operator = operator;
  30186. this._target = target;
  30187. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  30188. this._property = this._getProperty(this.propertyPath);
  30189. }
  30190. Object.defineProperty(ValueCondition, "IsEqual", {
  30191. get: function () {
  30192. return ValueCondition._IsEqual;
  30193. },
  30194. enumerable: true,
  30195. configurable: true
  30196. });
  30197. Object.defineProperty(ValueCondition, "IsDifferent", {
  30198. get: function () {
  30199. return ValueCondition._IsDifferent;
  30200. },
  30201. enumerable: true,
  30202. configurable: true
  30203. });
  30204. Object.defineProperty(ValueCondition, "IsGreater", {
  30205. get: function () {
  30206. return ValueCondition._IsGreater;
  30207. },
  30208. enumerable: true,
  30209. configurable: true
  30210. });
  30211. Object.defineProperty(ValueCondition, "IsLesser", {
  30212. get: function () {
  30213. return ValueCondition._IsLesser;
  30214. },
  30215. enumerable: true,
  30216. configurable: true
  30217. });
  30218. // Methods
  30219. ValueCondition.prototype.isValid = function () {
  30220. switch (this.operator) {
  30221. case ValueCondition.IsGreater:
  30222. return this._effectiveTarget[this._property] > this.value;
  30223. case ValueCondition.IsLesser:
  30224. return this._effectiveTarget[this._property] < this.value;
  30225. case ValueCondition.IsEqual:
  30226. case ValueCondition.IsDifferent:
  30227. var check;
  30228. if (this.value.equals) {
  30229. check = this.value.equals(this._effectiveTarget[this._property]);
  30230. }
  30231. else {
  30232. check = this.value === this._effectiveTarget[this._property];
  30233. }
  30234. return this.operator === ValueCondition.IsEqual ? check : !check;
  30235. }
  30236. return false;
  30237. };
  30238. ValueCondition.prototype.serialize = function () {
  30239. return this._serialize({
  30240. name: "ValueCondition",
  30241. properties: [
  30242. BABYLON.Action._GetTargetProperty(this._target),
  30243. { name: "propertyPath", value: this.propertyPath },
  30244. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  30245. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  30246. ]
  30247. });
  30248. };
  30249. ValueCondition.GetOperatorName = function (operator) {
  30250. switch (operator) {
  30251. case ValueCondition._IsEqual: return "IsEqual";
  30252. case ValueCondition._IsDifferent: return "IsDifferent";
  30253. case ValueCondition._IsGreater: return "IsGreater";
  30254. case ValueCondition._IsLesser: return "IsLesser";
  30255. default: return "";
  30256. }
  30257. };
  30258. // Statics
  30259. ValueCondition._IsEqual = 0;
  30260. ValueCondition._IsDifferent = 1;
  30261. ValueCondition._IsGreater = 2;
  30262. ValueCondition._IsLesser = 3;
  30263. return ValueCondition;
  30264. })(Condition);
  30265. BABYLON.ValueCondition = ValueCondition;
  30266. var PredicateCondition = (function (_super) {
  30267. __extends(PredicateCondition, _super);
  30268. function PredicateCondition(actionManager, predicate) {
  30269. _super.call(this, actionManager);
  30270. this.predicate = predicate;
  30271. }
  30272. PredicateCondition.prototype.isValid = function () {
  30273. return this.predicate();
  30274. };
  30275. return PredicateCondition;
  30276. })(Condition);
  30277. BABYLON.PredicateCondition = PredicateCondition;
  30278. var StateCondition = (function (_super) {
  30279. __extends(StateCondition, _super);
  30280. function StateCondition(actionManager, target, value) {
  30281. _super.call(this, actionManager);
  30282. this.value = value;
  30283. this._target = target;
  30284. }
  30285. // Methods
  30286. StateCondition.prototype.isValid = function () {
  30287. return this._target.state === this.value;
  30288. };
  30289. StateCondition.prototype.serialize = function () {
  30290. return this._serialize({
  30291. name: "StateCondition",
  30292. properties: [
  30293. BABYLON.Action._GetTargetProperty(this._target),
  30294. { name: "value", value: this.value }
  30295. ]
  30296. });
  30297. };
  30298. return StateCondition;
  30299. })(Condition);
  30300. BABYLON.StateCondition = StateCondition;
  30301. })(BABYLON || (BABYLON = {}));
  30302. var BABYLON;
  30303. (function (BABYLON) {
  30304. var Action = (function () {
  30305. function Action(triggerOptions, condition) {
  30306. this.triggerOptions = triggerOptions;
  30307. if (triggerOptions.parameter) {
  30308. this.trigger = triggerOptions.trigger;
  30309. this._triggerParameter = triggerOptions.parameter;
  30310. }
  30311. else {
  30312. this.trigger = triggerOptions;
  30313. }
  30314. this._nextActiveAction = this;
  30315. this._condition = condition;
  30316. }
  30317. // Methods
  30318. Action.prototype._prepare = function () {
  30319. };
  30320. Action.prototype.getTriggerParameter = function () {
  30321. return this._triggerParameter;
  30322. };
  30323. Action.prototype._executeCurrent = function (evt) {
  30324. if (this._nextActiveAction._condition) {
  30325. var condition = this._nextActiveAction._condition;
  30326. var currentRenderId = this._actionManager.getScene().getRenderId();
  30327. // We cache the current evaluation for the current frame
  30328. if (condition._evaluationId === currentRenderId) {
  30329. if (!condition._currentResult) {
  30330. return;
  30331. }
  30332. }
  30333. else {
  30334. condition._evaluationId = currentRenderId;
  30335. if (!condition.isValid()) {
  30336. condition._currentResult = false;
  30337. return;
  30338. }
  30339. condition._currentResult = true;
  30340. }
  30341. }
  30342. this._nextActiveAction.execute(evt);
  30343. this.skipToNextActiveAction();
  30344. };
  30345. Action.prototype.execute = function (evt) {
  30346. };
  30347. Action.prototype.skipToNextActiveAction = function () {
  30348. if (this._nextActiveAction._child) {
  30349. if (!this._nextActiveAction._child._actionManager) {
  30350. this._nextActiveAction._child._actionManager = this._actionManager;
  30351. }
  30352. this._nextActiveAction = this._nextActiveAction._child;
  30353. }
  30354. else {
  30355. this._nextActiveAction = this;
  30356. }
  30357. };
  30358. Action.prototype.then = function (action) {
  30359. this._child = action;
  30360. action._actionManager = this._actionManager;
  30361. action._prepare();
  30362. return action;
  30363. };
  30364. Action.prototype._getProperty = function (propertyPath) {
  30365. return this._actionManager._getProperty(propertyPath);
  30366. };
  30367. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  30368. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30369. };
  30370. Action.prototype.serialize = function (parent) {
  30371. };
  30372. // Called by BABYLON.Action objects in serialize(...). Internal use
  30373. Action.prototype._serialize = function (serializedAction, parent) {
  30374. var serializationObject = {
  30375. type: 1,
  30376. children: [],
  30377. name: serializedAction.name,
  30378. properties: serializedAction.properties || []
  30379. };
  30380. // Serialize child
  30381. if (this._child) {
  30382. this._child.serialize(serializationObject);
  30383. }
  30384. // Check if "this" has a condition
  30385. if (this._condition) {
  30386. var serializedCondition = this._condition.serialize();
  30387. serializedCondition.children.push(serializationObject);
  30388. if (parent) {
  30389. parent.children.push(serializedCondition);
  30390. }
  30391. return serializedCondition;
  30392. }
  30393. if (parent) {
  30394. parent.children.push(serializationObject);
  30395. }
  30396. return serializationObject;
  30397. };
  30398. Action._SerializeValueAsString = function (value) {
  30399. if (typeof value === "number") {
  30400. return value.toString();
  30401. }
  30402. if (typeof value === "boolean") {
  30403. return value ? "true" : "false";
  30404. }
  30405. if (value instanceof BABYLON.Vector2) {
  30406. return value.x + ", " + value.y;
  30407. }
  30408. if (value instanceof BABYLON.Vector3) {
  30409. return value.x + ", " + value.y + ", " + value.z;
  30410. }
  30411. if (value instanceof BABYLON.Color3) {
  30412. return value.r + ", " + value.g + ", " + value.b;
  30413. }
  30414. if (value instanceof BABYLON.Color4) {
  30415. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  30416. }
  30417. return value; // string
  30418. };
  30419. Action._GetTargetProperty = function (target) {
  30420. return {
  30421. name: "target",
  30422. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  30423. : target instanceof BABYLON.Light ? "LightProperties"
  30424. : target instanceof BABYLON.Camera ? "CameraProperties"
  30425. : "SceneProperties",
  30426. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  30427. };
  30428. };
  30429. return Action;
  30430. })();
  30431. BABYLON.Action = Action;
  30432. })(BABYLON || (BABYLON = {}));
  30433. var BABYLON;
  30434. (function (BABYLON) {
  30435. /**
  30436. * ActionEvent is the event beint sent when an action is triggered.
  30437. */
  30438. var ActionEvent = (function () {
  30439. /**
  30440. * @constructor
  30441. * @param source The mesh or sprite that triggered the action.
  30442. * @param pointerX The X mouse cursor position at the time of the event
  30443. * @param pointerY The Y mouse cursor position at the time of the event
  30444. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  30445. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  30446. */
  30447. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  30448. this.source = source;
  30449. this.pointerX = pointerX;
  30450. this.pointerY = pointerY;
  30451. this.meshUnderPointer = meshUnderPointer;
  30452. this.sourceEvent = sourceEvent;
  30453. this.additionalData = additionalData;
  30454. }
  30455. /**
  30456. * Helper function to auto-create an ActionEvent from a source mesh.
  30457. * @param source The source mesh that triggered the event
  30458. * @param evt {Event} The original (browser) event
  30459. */
  30460. ActionEvent.CreateNew = function (source, evt, additionalData) {
  30461. var scene = source.getScene();
  30462. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30463. };
  30464. /**
  30465. * Helper function to auto-create an ActionEvent from a source mesh.
  30466. * @param source The source sprite that triggered the event
  30467. * @param scene Scene associated with the sprite
  30468. * @param evt {Event} The original (browser) event
  30469. */
  30470. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  30471. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30472. };
  30473. /**
  30474. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  30475. * @param scene the scene where the event occurred
  30476. * @param evt {Event} The original (browser) event
  30477. */
  30478. ActionEvent.CreateNewFromScene = function (scene, evt) {
  30479. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  30480. };
  30481. return ActionEvent;
  30482. })();
  30483. BABYLON.ActionEvent = ActionEvent;
  30484. /**
  30485. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  30486. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  30487. */
  30488. var ActionManager = (function () {
  30489. function ActionManager(scene) {
  30490. // Members
  30491. this.actions = new Array();
  30492. this._scene = scene;
  30493. scene._actionManagers.push(this);
  30494. }
  30495. Object.defineProperty(ActionManager, "NothingTrigger", {
  30496. get: function () {
  30497. return ActionManager._NothingTrigger;
  30498. },
  30499. enumerable: true,
  30500. configurable: true
  30501. });
  30502. Object.defineProperty(ActionManager, "OnPickTrigger", {
  30503. get: function () {
  30504. return ActionManager._OnPickTrigger;
  30505. },
  30506. enumerable: true,
  30507. configurable: true
  30508. });
  30509. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  30510. get: function () {
  30511. return ActionManager._OnLeftPickTrigger;
  30512. },
  30513. enumerable: true,
  30514. configurable: true
  30515. });
  30516. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  30517. get: function () {
  30518. return ActionManager._OnRightPickTrigger;
  30519. },
  30520. enumerable: true,
  30521. configurable: true
  30522. });
  30523. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  30524. get: function () {
  30525. return ActionManager._OnCenterPickTrigger;
  30526. },
  30527. enumerable: true,
  30528. configurable: true
  30529. });
  30530. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  30531. get: function () {
  30532. return ActionManager._OnPickDownTrigger;
  30533. },
  30534. enumerable: true,
  30535. configurable: true
  30536. });
  30537. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  30538. get: function () {
  30539. return ActionManager._OnPickUpTrigger;
  30540. },
  30541. enumerable: true,
  30542. configurable: true
  30543. });
  30544. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  30545. /// This trigger will only be raised if you also declared a OnPickDown
  30546. get: function () {
  30547. return ActionManager._OnPickOutTrigger;
  30548. },
  30549. enumerable: true,
  30550. configurable: true
  30551. });
  30552. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  30553. get: function () {
  30554. return ActionManager._OnLongPressTrigger;
  30555. },
  30556. enumerable: true,
  30557. configurable: true
  30558. });
  30559. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  30560. get: function () {
  30561. return ActionManager._OnPointerOverTrigger;
  30562. },
  30563. enumerable: true,
  30564. configurable: true
  30565. });
  30566. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  30567. get: function () {
  30568. return ActionManager._OnPointerOutTrigger;
  30569. },
  30570. enumerable: true,
  30571. configurable: true
  30572. });
  30573. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  30574. get: function () {
  30575. return ActionManager._OnEveryFrameTrigger;
  30576. },
  30577. enumerable: true,
  30578. configurable: true
  30579. });
  30580. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  30581. get: function () {
  30582. return ActionManager._OnIntersectionEnterTrigger;
  30583. },
  30584. enumerable: true,
  30585. configurable: true
  30586. });
  30587. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  30588. get: function () {
  30589. return ActionManager._OnIntersectionExitTrigger;
  30590. },
  30591. enumerable: true,
  30592. configurable: true
  30593. });
  30594. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  30595. get: function () {
  30596. return ActionManager._OnKeyDownTrigger;
  30597. },
  30598. enumerable: true,
  30599. configurable: true
  30600. });
  30601. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  30602. get: function () {
  30603. return ActionManager._OnKeyUpTrigger;
  30604. },
  30605. enumerable: true,
  30606. configurable: true
  30607. });
  30608. // Methods
  30609. ActionManager.prototype.dispose = function () {
  30610. var index = this._scene._actionManagers.indexOf(this);
  30611. if (index > -1) {
  30612. this._scene._actionManagers.splice(index, 1);
  30613. }
  30614. };
  30615. ActionManager.prototype.getScene = function () {
  30616. return this._scene;
  30617. };
  30618. /**
  30619. * Does this action manager handles actions of any of the given triggers
  30620. * @param {number[]} triggers - the triggers to be tested
  30621. * @return {boolean} whether one (or more) of the triggers is handeled
  30622. */
  30623. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  30624. for (var index = 0; index < this.actions.length; index++) {
  30625. var action = this.actions[index];
  30626. if (triggers.indexOf(action.trigger) > -1) {
  30627. return true;
  30628. }
  30629. }
  30630. return false;
  30631. };
  30632. /**
  30633. * Does this action manager handles actions of a given trigger
  30634. * @param {number} trigger - the trigger to be tested
  30635. * @return {boolean} whether the trigger is handeled
  30636. */
  30637. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  30638. for (var index = 0; index < this.actions.length; index++) {
  30639. var action = this.actions[index];
  30640. if (action.trigger === trigger) {
  30641. return true;
  30642. }
  30643. }
  30644. return false;
  30645. };
  30646. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  30647. /**
  30648. * Does this action manager has pointer triggers
  30649. * @return {boolean} whether or not it has pointer triggers
  30650. */
  30651. get: function () {
  30652. for (var index = 0; index < this.actions.length; index++) {
  30653. var action = this.actions[index];
  30654. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  30655. return true;
  30656. }
  30657. }
  30658. return false;
  30659. },
  30660. enumerable: true,
  30661. configurable: true
  30662. });
  30663. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  30664. /**
  30665. * Does this action manager has pick triggers
  30666. * @return {boolean} whether or not it has pick triggers
  30667. */
  30668. get: function () {
  30669. for (var index = 0; index < this.actions.length; index++) {
  30670. var action = this.actions[index];
  30671. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  30672. return true;
  30673. }
  30674. }
  30675. return false;
  30676. },
  30677. enumerable: true,
  30678. configurable: true
  30679. });
  30680. /**
  30681. * Registers an action to this action manager
  30682. * @param {BABYLON.Action} action - the action to be registered
  30683. * @return {BABYLON.Action} the action amended (prepared) after registration
  30684. */
  30685. ActionManager.prototype.registerAction = function (action) {
  30686. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  30687. if (this.getScene().actionManager !== this) {
  30688. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  30689. return null;
  30690. }
  30691. }
  30692. this.actions.push(action);
  30693. action._actionManager = this;
  30694. action._prepare();
  30695. return action;
  30696. };
  30697. /**
  30698. * Process a specific trigger
  30699. * @param {number} trigger - the trigger to process
  30700. * @param evt {BABYLON.ActionEvent} the event details to be processed
  30701. */
  30702. ActionManager.prototype.processTrigger = function (trigger, evt) {
  30703. for (var index = 0; index < this.actions.length; index++) {
  30704. var action = this.actions[index];
  30705. if (action.trigger === trigger) {
  30706. if (trigger === ActionManager.OnKeyUpTrigger
  30707. || trigger === ActionManager.OnKeyDownTrigger) {
  30708. var parameter = action.getTriggerParameter();
  30709. if (parameter) {
  30710. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  30711. var actualkey = String.fromCharCode(unicode).toLowerCase();
  30712. if (actualkey !== parameter.toLowerCase()) {
  30713. continue;
  30714. }
  30715. }
  30716. }
  30717. action._executeCurrent(evt);
  30718. }
  30719. }
  30720. };
  30721. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  30722. var properties = propertyPath.split(".");
  30723. for (var index = 0; index < properties.length - 1; index++) {
  30724. target = target[properties[index]];
  30725. }
  30726. return target;
  30727. };
  30728. ActionManager.prototype._getProperty = function (propertyPath) {
  30729. var properties = propertyPath.split(".");
  30730. return properties[properties.length - 1];
  30731. };
  30732. ActionManager.prototype.serialize = function (name) {
  30733. var root = {
  30734. children: [],
  30735. name: name,
  30736. type: 3,
  30737. properties: [] // Empty for root but required
  30738. };
  30739. for (var i = 0; i < this.actions.length; i++) {
  30740. var triggerObject = {
  30741. type: 0,
  30742. children: [],
  30743. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  30744. properties: []
  30745. };
  30746. var triggerOptions = this.actions[i].triggerOptions;
  30747. if (triggerOptions && typeof triggerOptions !== "number") {
  30748. if (triggerOptions.parameter instanceof BABYLON.Node) {
  30749. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  30750. }
  30751. else {
  30752. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  30753. }
  30754. }
  30755. // Serialize child action, recursively
  30756. this.actions[i].serialize(triggerObject);
  30757. // Add serialized trigger
  30758. root.children.push(triggerObject);
  30759. }
  30760. return root;
  30761. };
  30762. ActionManager.Parse = function (parsedActions, object, scene) {
  30763. var actionManager = new BABYLON.ActionManager(scene);
  30764. if (object === null)
  30765. scene.actionManager = actionManager;
  30766. else
  30767. object.actionManager = actionManager;
  30768. // instanciate a new object
  30769. var instanciate = function (name, params) {
  30770. var newInstance = Object.create(BABYLON[name].prototype);
  30771. newInstance.constructor.apply(newInstance, params);
  30772. return newInstance;
  30773. };
  30774. var parseParameter = function (name, value, target, propertyPath) {
  30775. if (propertyPath === null) {
  30776. // String, boolean or float
  30777. var floatValue = parseFloat(value);
  30778. if (value === "true" || value === "false")
  30779. return value === "true";
  30780. else
  30781. return isNaN(floatValue) ? value : floatValue;
  30782. }
  30783. var effectiveTarget = propertyPath.split(".");
  30784. var values = value.split(",");
  30785. // Get effective Target
  30786. for (var i = 0; i < effectiveTarget.length; i++) {
  30787. target = target[effectiveTarget[i]];
  30788. }
  30789. // Return appropriate value with its type
  30790. if (typeof (target) === "boolean")
  30791. return values[0] === "true";
  30792. if (typeof (target) === "string")
  30793. return values[0];
  30794. // Parameters with multiple values such as Vector3 etc.
  30795. var split = new Array();
  30796. for (var i = 0; i < values.length; i++)
  30797. split.push(parseFloat(values[i]));
  30798. if (target instanceof BABYLON.Vector3)
  30799. return BABYLON.Vector3.FromArray(split);
  30800. if (target instanceof BABYLON.Vector4)
  30801. return BABYLON.Vector4.FromArray(split);
  30802. if (target instanceof BABYLON.Color3)
  30803. return BABYLON.Color3.FromArray(split);
  30804. if (target instanceof BABYLON.Color4)
  30805. return BABYLON.Color4.FromArray(split);
  30806. return parseFloat(values[0]);
  30807. };
  30808. // traverse graph per trigger
  30809. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  30810. if (combineArray === void 0) { combineArray = null; }
  30811. if (parsedAction.detached)
  30812. return;
  30813. var parameters = new Array();
  30814. var target = null;
  30815. var propertyPath = null;
  30816. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  30817. // Parameters
  30818. if (parsedAction.type === 2)
  30819. parameters.push(actionManager);
  30820. else
  30821. parameters.push(trigger);
  30822. if (combine) {
  30823. var actions = new Array();
  30824. for (var j = 0; j < parsedAction.combine.length; j++) {
  30825. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  30826. }
  30827. parameters.push(actions);
  30828. }
  30829. else {
  30830. for (var i = 0; i < parsedAction.properties.length; i++) {
  30831. var value = parsedAction.properties[i].value;
  30832. var name = parsedAction.properties[i].name;
  30833. var targetType = parsedAction.properties[i].targetType;
  30834. if (name === "target")
  30835. if (targetType !== null && targetType === "SceneProperties")
  30836. value = target = scene;
  30837. else
  30838. value = target = scene.getNodeByName(value);
  30839. else if (name === "parent")
  30840. value = scene.getNodeByName(value);
  30841. else if (name === "sound")
  30842. value = scene.getSoundByName(value);
  30843. else if (name !== "propertyPath") {
  30844. if (parsedAction.type === 2 && name === "operator")
  30845. value = BABYLON.ValueCondition[value];
  30846. else
  30847. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  30848. }
  30849. else {
  30850. propertyPath = value;
  30851. }
  30852. parameters.push(value);
  30853. }
  30854. }
  30855. if (combineArray === null) {
  30856. parameters.push(condition);
  30857. }
  30858. else {
  30859. parameters.push(null);
  30860. }
  30861. // If interpolate value action
  30862. if (parsedAction.name === "InterpolateValueAction") {
  30863. var param = parameters[parameters.length - 2];
  30864. parameters[parameters.length - 1] = param;
  30865. parameters[parameters.length - 2] = condition;
  30866. }
  30867. // Action or condition(s) and not CombineAction
  30868. var newAction = instanciate(parsedAction.name, parameters);
  30869. if (newAction instanceof BABYLON.Condition && condition !== null) {
  30870. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  30871. if (action)
  30872. action.then(nothing);
  30873. else
  30874. actionManager.registerAction(nothing);
  30875. action = nothing;
  30876. }
  30877. if (combineArray === null) {
  30878. if (newAction instanceof BABYLON.Condition) {
  30879. condition = newAction;
  30880. newAction = action;
  30881. }
  30882. else {
  30883. condition = null;
  30884. if (action)
  30885. action.then(newAction);
  30886. else
  30887. actionManager.registerAction(newAction);
  30888. }
  30889. }
  30890. else {
  30891. combineArray.push(newAction);
  30892. }
  30893. for (var i = 0; i < parsedAction.children.length; i++)
  30894. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  30895. };
  30896. // triggers
  30897. for (var i = 0; i < parsedActions.children.length; i++) {
  30898. var triggerParams;
  30899. var trigger = parsedActions.children[i];
  30900. if (trigger.properties.length > 0) {
  30901. var param = trigger.properties[0].value;
  30902. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  30903. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  30904. }
  30905. else
  30906. triggerParams = BABYLON.ActionManager[trigger.name];
  30907. for (var j = 0; j < trigger.children.length; j++) {
  30908. if (!trigger.detached)
  30909. traverse(trigger.children[j], triggerParams, null, null);
  30910. }
  30911. }
  30912. };
  30913. ActionManager.GetTriggerName = function (trigger) {
  30914. switch (trigger) {
  30915. case 0: return "NothingTrigger";
  30916. case 1: return "OnPickTrigger";
  30917. case 2: return "OnLeftPickTrigger";
  30918. case 3: return "OnRightPickTrigger";
  30919. case 4: return "OnCenterPickTrigger";
  30920. case 5: return "OnPickDownTrigger";
  30921. case 6: return "OnPickUpTrigger";
  30922. case 7: return "OnLongPressTrigger";
  30923. case 8: return "OnPointerOverTrigger";
  30924. case 9: return "OnPointerOutTrigger";
  30925. case 10: return "OnEveryFrameTrigger";
  30926. case 11: return "OnIntersectionEnterTrigger";
  30927. case 12: return "OnIntersectionExitTrigger";
  30928. case 13: return "OnKeyDownTrigger";
  30929. case 14: return "OnKeyUpTrigger";
  30930. case 15: return "OnPickOutTrigger";
  30931. default: return "";
  30932. }
  30933. };
  30934. // Statics
  30935. ActionManager._NothingTrigger = 0;
  30936. ActionManager._OnPickTrigger = 1;
  30937. ActionManager._OnLeftPickTrigger = 2;
  30938. ActionManager._OnRightPickTrigger = 3;
  30939. ActionManager._OnCenterPickTrigger = 4;
  30940. ActionManager._OnPickDownTrigger = 5;
  30941. ActionManager._OnPickUpTrigger = 6;
  30942. ActionManager._OnLongPressTrigger = 7;
  30943. ActionManager._OnPointerOverTrigger = 8;
  30944. ActionManager._OnPointerOutTrigger = 9;
  30945. ActionManager._OnEveryFrameTrigger = 10;
  30946. ActionManager._OnIntersectionEnterTrigger = 11;
  30947. ActionManager._OnIntersectionExitTrigger = 12;
  30948. ActionManager._OnKeyDownTrigger = 13;
  30949. ActionManager._OnKeyUpTrigger = 14;
  30950. ActionManager._OnPickOutTrigger = 15;
  30951. ActionManager.DragMovementThreshold = 10; // in pixels
  30952. ActionManager.LongPressDelay = 500; // in milliseconds
  30953. return ActionManager;
  30954. })();
  30955. BABYLON.ActionManager = ActionManager;
  30956. })(BABYLON || (BABYLON = {}));
  30957. var BABYLON;
  30958. (function (BABYLON) {
  30959. var InterpolateValueAction = (function (_super) {
  30960. __extends(InterpolateValueAction, _super);
  30961. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  30962. if (duration === void 0) { duration = 1000; }
  30963. _super.call(this, triggerOptions, condition);
  30964. this.propertyPath = propertyPath;
  30965. this.value = value;
  30966. this.duration = duration;
  30967. this.stopOtherAnimations = stopOtherAnimations;
  30968. this.onInterpolationDone = onInterpolationDone;
  30969. this._target = this._effectiveTarget = target;
  30970. }
  30971. InterpolateValueAction.prototype._prepare = function () {
  30972. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  30973. this._property = this._getProperty(this.propertyPath);
  30974. };
  30975. InterpolateValueAction.prototype.execute = function () {
  30976. var scene = this._actionManager.getScene();
  30977. var keys = [
  30978. {
  30979. frame: 0,
  30980. value: this._effectiveTarget[this._property]
  30981. }, {
  30982. frame: 100,
  30983. value: this.value
  30984. }
  30985. ];
  30986. var dataType;
  30987. if (typeof this.value === "number") {
  30988. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  30989. }
  30990. else if (this.value instanceof BABYLON.Color3) {
  30991. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  30992. }
  30993. else if (this.value instanceof BABYLON.Vector3) {
  30994. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  30995. }
  30996. else if (this.value instanceof BABYLON.Matrix) {
  30997. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  30998. }
  30999. else if (this.value instanceof BABYLON.Quaternion) {
  31000. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  31001. }
  31002. else {
  31003. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  31004. return;
  31005. }
  31006. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  31007. animation.setKeys(keys);
  31008. if (this.stopOtherAnimations) {
  31009. scene.stopAnimation(this._effectiveTarget);
  31010. }
  31011. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  31012. };
  31013. InterpolateValueAction.prototype.serialize = function (parent) {
  31014. return _super.prototype._serialize.call(this, {
  31015. name: "InterpolateValueAction",
  31016. properties: [
  31017. BABYLON.Action._GetTargetProperty(this._target),
  31018. { name: "propertyPath", value: this.propertyPath },
  31019. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31020. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  31021. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  31022. ]
  31023. }, parent);
  31024. };
  31025. return InterpolateValueAction;
  31026. })(BABYLON.Action);
  31027. BABYLON.InterpolateValueAction = InterpolateValueAction;
  31028. })(BABYLON || (BABYLON = {}));
  31029. var BABYLON;
  31030. (function (BABYLON) {
  31031. var SwitchBooleanAction = (function (_super) {
  31032. __extends(SwitchBooleanAction, _super);
  31033. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  31034. _super.call(this, triggerOptions, condition);
  31035. this.propertyPath = propertyPath;
  31036. this._target = this._effectiveTarget = target;
  31037. }
  31038. SwitchBooleanAction.prototype._prepare = function () {
  31039. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31040. this._property = this._getProperty(this.propertyPath);
  31041. };
  31042. SwitchBooleanAction.prototype.execute = function () {
  31043. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  31044. };
  31045. SwitchBooleanAction.prototype.serialize = function (parent) {
  31046. return _super.prototype._serialize.call(this, {
  31047. name: "SwitchBooleanAction",
  31048. properties: [
  31049. BABYLON.Action._GetTargetProperty(this._target),
  31050. { name: "propertyPath", value: this.propertyPath }
  31051. ]
  31052. }, parent);
  31053. };
  31054. return SwitchBooleanAction;
  31055. })(BABYLON.Action);
  31056. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  31057. var SetStateAction = (function (_super) {
  31058. __extends(SetStateAction, _super);
  31059. function SetStateAction(triggerOptions, target, value, condition) {
  31060. _super.call(this, triggerOptions, condition);
  31061. this.value = value;
  31062. this._target = target;
  31063. }
  31064. SetStateAction.prototype.execute = function () {
  31065. this._target.state = this.value;
  31066. };
  31067. SetStateAction.prototype.serialize = function (parent) {
  31068. return _super.prototype._serialize.call(this, {
  31069. name: "SetStateAction",
  31070. properties: [
  31071. BABYLON.Action._GetTargetProperty(this._target),
  31072. { name: "value", value: this.value }
  31073. ]
  31074. }, parent);
  31075. };
  31076. return SetStateAction;
  31077. })(BABYLON.Action);
  31078. BABYLON.SetStateAction = SetStateAction;
  31079. var SetValueAction = (function (_super) {
  31080. __extends(SetValueAction, _super);
  31081. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  31082. _super.call(this, triggerOptions, condition);
  31083. this.propertyPath = propertyPath;
  31084. this.value = value;
  31085. this._target = this._effectiveTarget = target;
  31086. }
  31087. SetValueAction.prototype._prepare = function () {
  31088. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31089. this._property = this._getProperty(this.propertyPath);
  31090. };
  31091. SetValueAction.prototype.execute = function () {
  31092. this._effectiveTarget[this._property] = this.value;
  31093. };
  31094. SetValueAction.prototype.serialize = function (parent) {
  31095. return _super.prototype._serialize.call(this, {
  31096. name: "SetValueAction",
  31097. properties: [
  31098. BABYLON.Action._GetTargetProperty(this._target),
  31099. { name: "propertyPath", value: this.propertyPath },
  31100. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31101. ]
  31102. }, parent);
  31103. };
  31104. return SetValueAction;
  31105. })(BABYLON.Action);
  31106. BABYLON.SetValueAction = SetValueAction;
  31107. var IncrementValueAction = (function (_super) {
  31108. __extends(IncrementValueAction, _super);
  31109. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  31110. _super.call(this, triggerOptions, condition);
  31111. this.propertyPath = propertyPath;
  31112. this.value = value;
  31113. this._target = this._effectiveTarget = target;
  31114. }
  31115. IncrementValueAction.prototype._prepare = function () {
  31116. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31117. this._property = this._getProperty(this.propertyPath);
  31118. if (typeof this._effectiveTarget[this._property] !== "number") {
  31119. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  31120. }
  31121. };
  31122. IncrementValueAction.prototype.execute = function () {
  31123. this._effectiveTarget[this._property] += this.value;
  31124. };
  31125. IncrementValueAction.prototype.serialize = function (parent) {
  31126. return _super.prototype._serialize.call(this, {
  31127. name: "IncrementValueAction",
  31128. properties: [
  31129. BABYLON.Action._GetTargetProperty(this._target),
  31130. { name: "propertyPath", value: this.propertyPath },
  31131. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31132. ]
  31133. }, parent);
  31134. };
  31135. return IncrementValueAction;
  31136. })(BABYLON.Action);
  31137. BABYLON.IncrementValueAction = IncrementValueAction;
  31138. var PlayAnimationAction = (function (_super) {
  31139. __extends(PlayAnimationAction, _super);
  31140. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  31141. _super.call(this, triggerOptions, condition);
  31142. this.from = from;
  31143. this.to = to;
  31144. this.loop = loop;
  31145. this._target = target;
  31146. }
  31147. PlayAnimationAction.prototype._prepare = function () {
  31148. };
  31149. PlayAnimationAction.prototype.execute = function () {
  31150. var scene = this._actionManager.getScene();
  31151. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  31152. };
  31153. PlayAnimationAction.prototype.serialize = function (parent) {
  31154. return _super.prototype._serialize.call(this, {
  31155. name: "PlayAnimationAction",
  31156. properties: [
  31157. BABYLON.Action._GetTargetProperty(this._target),
  31158. { name: "from", value: String(this.from) },
  31159. { name: "to", value: String(this.to) },
  31160. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  31161. ]
  31162. }, parent);
  31163. };
  31164. return PlayAnimationAction;
  31165. })(BABYLON.Action);
  31166. BABYLON.PlayAnimationAction = PlayAnimationAction;
  31167. var StopAnimationAction = (function (_super) {
  31168. __extends(StopAnimationAction, _super);
  31169. function StopAnimationAction(triggerOptions, target, condition) {
  31170. _super.call(this, triggerOptions, condition);
  31171. this._target = target;
  31172. }
  31173. StopAnimationAction.prototype._prepare = function () {
  31174. };
  31175. StopAnimationAction.prototype.execute = function () {
  31176. var scene = this._actionManager.getScene();
  31177. scene.stopAnimation(this._target);
  31178. };
  31179. StopAnimationAction.prototype.serialize = function (parent) {
  31180. return _super.prototype._serialize.call(this, {
  31181. name: "StopAnimationAction",
  31182. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  31183. }, parent);
  31184. };
  31185. return StopAnimationAction;
  31186. })(BABYLON.Action);
  31187. BABYLON.StopAnimationAction = StopAnimationAction;
  31188. var DoNothingAction = (function (_super) {
  31189. __extends(DoNothingAction, _super);
  31190. function DoNothingAction(triggerOptions, condition) {
  31191. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  31192. _super.call(this, triggerOptions, condition);
  31193. }
  31194. DoNothingAction.prototype.execute = function () {
  31195. };
  31196. DoNothingAction.prototype.serialize = function (parent) {
  31197. return _super.prototype._serialize.call(this, {
  31198. name: "DoNothingAction",
  31199. properties: []
  31200. }, parent);
  31201. };
  31202. return DoNothingAction;
  31203. })(BABYLON.Action);
  31204. BABYLON.DoNothingAction = DoNothingAction;
  31205. var CombineAction = (function (_super) {
  31206. __extends(CombineAction, _super);
  31207. function CombineAction(triggerOptions, children, condition) {
  31208. _super.call(this, triggerOptions, condition);
  31209. this.children = children;
  31210. }
  31211. CombineAction.prototype._prepare = function () {
  31212. for (var index = 0; index < this.children.length; index++) {
  31213. this.children[index]._actionManager = this._actionManager;
  31214. this.children[index]._prepare();
  31215. }
  31216. };
  31217. CombineAction.prototype.execute = function (evt) {
  31218. for (var index = 0; index < this.children.length; index++) {
  31219. this.children[index].execute(evt);
  31220. }
  31221. };
  31222. CombineAction.prototype.serialize = function (parent) {
  31223. var serializationObject = _super.prototype._serialize.call(this, {
  31224. name: "CombineAction",
  31225. properties: [],
  31226. combine: []
  31227. }, parent);
  31228. for (var i = 0; i < this.children.length; i++) {
  31229. serializationObject.combine.push(this.children[i].serialize(null));
  31230. }
  31231. return serializationObject;
  31232. };
  31233. return CombineAction;
  31234. })(BABYLON.Action);
  31235. BABYLON.CombineAction = CombineAction;
  31236. var ExecuteCodeAction = (function (_super) {
  31237. __extends(ExecuteCodeAction, _super);
  31238. function ExecuteCodeAction(triggerOptions, func, condition) {
  31239. _super.call(this, triggerOptions, condition);
  31240. this.func = func;
  31241. }
  31242. ExecuteCodeAction.prototype.execute = function (evt) {
  31243. this.func(evt);
  31244. };
  31245. return ExecuteCodeAction;
  31246. })(BABYLON.Action);
  31247. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  31248. var SetParentAction = (function (_super) {
  31249. __extends(SetParentAction, _super);
  31250. function SetParentAction(triggerOptions, target, parent, condition) {
  31251. _super.call(this, triggerOptions, condition);
  31252. this._target = target;
  31253. this._parent = parent;
  31254. }
  31255. SetParentAction.prototype._prepare = function () {
  31256. };
  31257. SetParentAction.prototype.execute = function () {
  31258. if (this._target.parent === this._parent) {
  31259. return;
  31260. }
  31261. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  31262. invertParentWorldMatrix.invert();
  31263. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  31264. this._target.parent = this._parent;
  31265. };
  31266. SetParentAction.prototype.serialize = function (parent) {
  31267. return _super.prototype._serialize.call(this, {
  31268. name: "SetParentAction",
  31269. properties: [
  31270. BABYLON.Action._GetTargetProperty(this._target),
  31271. BABYLON.Action._GetTargetProperty(this._parent),
  31272. ]
  31273. }, parent);
  31274. };
  31275. return SetParentAction;
  31276. })(BABYLON.Action);
  31277. BABYLON.SetParentAction = SetParentAction;
  31278. var PlaySoundAction = (function (_super) {
  31279. __extends(PlaySoundAction, _super);
  31280. function PlaySoundAction(triggerOptions, sound, condition) {
  31281. _super.call(this, triggerOptions, condition);
  31282. this._sound = sound;
  31283. }
  31284. PlaySoundAction.prototype._prepare = function () {
  31285. };
  31286. PlaySoundAction.prototype.execute = function () {
  31287. if (this._sound !== undefined)
  31288. this._sound.play();
  31289. };
  31290. PlaySoundAction.prototype.serialize = function (parent) {
  31291. return _super.prototype._serialize.call(this, {
  31292. name: "PlaySoundAction",
  31293. properties: [{ name: "sound", value: this._sound.name }]
  31294. }, parent);
  31295. };
  31296. return PlaySoundAction;
  31297. })(BABYLON.Action);
  31298. BABYLON.PlaySoundAction = PlaySoundAction;
  31299. var StopSoundAction = (function (_super) {
  31300. __extends(StopSoundAction, _super);
  31301. function StopSoundAction(triggerOptions, sound, condition) {
  31302. _super.call(this, triggerOptions, condition);
  31303. this._sound = sound;
  31304. }
  31305. StopSoundAction.prototype._prepare = function () {
  31306. };
  31307. StopSoundAction.prototype.execute = function () {
  31308. if (this._sound !== undefined)
  31309. this._sound.stop();
  31310. };
  31311. StopSoundAction.prototype.serialize = function (parent) {
  31312. return _super.prototype._serialize.call(this, {
  31313. name: "StopSoundAction",
  31314. properties: [{ name: "sound", value: this._sound.name }]
  31315. }, parent);
  31316. };
  31317. return StopSoundAction;
  31318. })(BABYLON.Action);
  31319. BABYLON.StopSoundAction = StopSoundAction;
  31320. })(BABYLON || (BABYLON = {}));
  31321. var BABYLON;
  31322. (function (BABYLON) {
  31323. var Geometry = (function () {
  31324. function Geometry(id, scene, vertexData, updatable, mesh) {
  31325. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31326. this._totalVertices = 0;
  31327. this._isDisposed = false;
  31328. this.id = id;
  31329. this._engine = scene.getEngine();
  31330. this._meshes = [];
  31331. this._scene = scene;
  31332. //Init vertex buffer cache
  31333. this._vertexBuffers = {};
  31334. this._indices = [];
  31335. // vertexData
  31336. if (vertexData) {
  31337. this.setAllVerticesData(vertexData, updatable);
  31338. }
  31339. else {
  31340. this._totalVertices = 0;
  31341. this._indices = [];
  31342. }
  31343. // applyToMesh
  31344. if (mesh) {
  31345. if (mesh instanceof BABYLON.LinesMesh) {
  31346. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31347. this.updateExtend();
  31348. }
  31349. this.applyToMesh(mesh);
  31350. mesh.computeWorldMatrix(true);
  31351. }
  31352. }
  31353. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31354. /**
  31355. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  31356. * @returns The Bias Vector
  31357. */
  31358. get: function () {
  31359. return this._boundingBias;
  31360. },
  31361. set: function (value) {
  31362. if (this._boundingBias && this._boundingBias.equals(value)) {
  31363. return;
  31364. }
  31365. this._boundingBias = value.clone();
  31366. this.updateBoundingInfo(true, null);
  31367. },
  31368. enumerable: true,
  31369. configurable: true
  31370. });
  31371. Object.defineProperty(Geometry.prototype, "extend", {
  31372. get: function () {
  31373. return this._extend;
  31374. },
  31375. enumerable: true,
  31376. configurable: true
  31377. });
  31378. Geometry.prototype.getScene = function () {
  31379. return this._scene;
  31380. };
  31381. Geometry.prototype.getEngine = function () {
  31382. return this._engine;
  31383. };
  31384. Geometry.prototype.isReady = function () {
  31385. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31386. };
  31387. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31388. vertexData.applyToGeometry(this, updatable);
  31389. this.notifyUpdate();
  31390. };
  31391. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31392. if (this._vertexBuffers[kind]) {
  31393. this._vertexBuffers[kind].dispose();
  31394. }
  31395. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31396. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31397. stride = this._vertexBuffers[kind].getStrideSize();
  31398. this._totalVertices = data.length / stride;
  31399. this.updateExtend(data);
  31400. var meshes = this._meshes;
  31401. var numOfMeshes = meshes.length;
  31402. for (var index = 0; index < numOfMeshes; index++) {
  31403. var mesh = meshes[index];
  31404. mesh._resetPointsArrayCache();
  31405. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31406. mesh._createGlobalSubMesh();
  31407. mesh.computeWorldMatrix(true);
  31408. }
  31409. }
  31410. this.notifyUpdate(kind);
  31411. };
  31412. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31413. var vertexBuffer = this.getVertexBuffer(kind);
  31414. if (!vertexBuffer) {
  31415. return;
  31416. }
  31417. vertexBuffer.updateDirectly(data, offset);
  31418. this.notifyUpdate(kind);
  31419. };
  31420. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31421. var vertexBuffer = this.getVertexBuffer(kind);
  31422. if (!vertexBuffer) {
  31423. return;
  31424. }
  31425. vertexBuffer.update(data);
  31426. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31427. var stride = vertexBuffer.getStrideSize();
  31428. this._totalVertices = data.length / stride;
  31429. this.updateBoundingInfo(updateExtends, data);
  31430. }
  31431. this.notifyUpdate(kind);
  31432. };
  31433. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31434. if (updateExtends) {
  31435. this.updateExtend(data);
  31436. }
  31437. var meshes = this._meshes;
  31438. var numOfMeshes = meshes.length;
  31439. for (var index = 0; index < numOfMeshes; index++) {
  31440. var mesh = meshes[index];
  31441. mesh._resetPointsArrayCache();
  31442. if (updateExtends) {
  31443. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31444. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31445. var subMesh = mesh.subMeshes[subIndex];
  31446. subMesh.refreshBoundingInfo();
  31447. }
  31448. }
  31449. }
  31450. };
  31451. Geometry.prototype.getTotalVertices = function () {
  31452. if (!this.isReady()) {
  31453. return 0;
  31454. }
  31455. return this._totalVertices;
  31456. };
  31457. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  31458. var vertexBuffer = this.getVertexBuffer(kind);
  31459. if (!vertexBuffer) {
  31460. return null;
  31461. }
  31462. var orig = vertexBuffer.getData();
  31463. if (!copyWhenShared || this._meshes.length === 1) {
  31464. return orig;
  31465. }
  31466. else {
  31467. var len = orig.length;
  31468. var copy = [];
  31469. for (var i = 0; i < len; i++) {
  31470. copy.push(orig[i]);
  31471. }
  31472. return copy;
  31473. }
  31474. };
  31475. Geometry.prototype.getVertexBuffer = function (kind) {
  31476. if (!this.isReady()) {
  31477. return null;
  31478. }
  31479. return this._vertexBuffers[kind];
  31480. };
  31481. Geometry.prototype.getVertexBuffers = function () {
  31482. if (!this.isReady()) {
  31483. return null;
  31484. }
  31485. return this._vertexBuffers;
  31486. };
  31487. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31488. if (!this._vertexBuffers) {
  31489. if (this._delayInfo) {
  31490. return this._delayInfo.indexOf(kind) !== -1;
  31491. }
  31492. return false;
  31493. }
  31494. return this._vertexBuffers[kind] !== undefined;
  31495. };
  31496. Geometry.prototype.getVerticesDataKinds = function () {
  31497. var result = [];
  31498. var kind;
  31499. if (!this._vertexBuffers && this._delayInfo) {
  31500. for (kind in this._delayInfo) {
  31501. result.push(kind);
  31502. }
  31503. }
  31504. else {
  31505. for (kind in this._vertexBuffers) {
  31506. result.push(kind);
  31507. }
  31508. }
  31509. return result;
  31510. };
  31511. Geometry.prototype.setIndices = function (indices, totalVertices) {
  31512. if (this._indexBuffer) {
  31513. this._engine._releaseBuffer(this._indexBuffer);
  31514. }
  31515. this._indices = indices;
  31516. if (this._meshes.length !== 0 && this._indices) {
  31517. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31518. }
  31519. if (totalVertices !== undefined) {
  31520. this._totalVertices = totalVertices;
  31521. }
  31522. var meshes = this._meshes;
  31523. var numOfMeshes = meshes.length;
  31524. for (var index = 0; index < numOfMeshes; index++) {
  31525. meshes[index]._createGlobalSubMesh();
  31526. }
  31527. this.notifyUpdate();
  31528. };
  31529. Geometry.prototype.getTotalIndices = function () {
  31530. if (!this.isReady()) {
  31531. return 0;
  31532. }
  31533. return this._indices.length;
  31534. };
  31535. Geometry.prototype.getIndices = function (copyWhenShared) {
  31536. if (!this.isReady()) {
  31537. return null;
  31538. }
  31539. var orig = this._indices;
  31540. if (!copyWhenShared || this._meshes.length === 1) {
  31541. return orig;
  31542. }
  31543. else {
  31544. var len = orig.length;
  31545. var copy = [];
  31546. for (var i = 0; i < len; i++) {
  31547. copy.push(orig[i]);
  31548. }
  31549. return copy;
  31550. }
  31551. };
  31552. Geometry.prototype.getIndexBuffer = function () {
  31553. if (!this.isReady()) {
  31554. return null;
  31555. }
  31556. return this._indexBuffer;
  31557. };
  31558. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31559. var meshes = this._meshes;
  31560. var index = meshes.indexOf(mesh);
  31561. if (index === -1) {
  31562. return;
  31563. }
  31564. for (var kind in this._vertexBuffers) {
  31565. this._vertexBuffers[kind].dispose();
  31566. }
  31567. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  31568. this._indexBuffer = null;
  31569. }
  31570. meshes.splice(index, 1);
  31571. mesh._geometry = null;
  31572. if (meshes.length === 0 && shouldDispose) {
  31573. this.dispose();
  31574. }
  31575. };
  31576. Geometry.prototype.applyToMesh = function (mesh) {
  31577. if (mesh._geometry === this) {
  31578. return;
  31579. }
  31580. var previousGeometry = mesh._geometry;
  31581. if (previousGeometry) {
  31582. previousGeometry.releaseForMesh(mesh);
  31583. }
  31584. var meshes = this._meshes;
  31585. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31586. mesh._geometry = this;
  31587. this._scene.pushGeometry(this);
  31588. meshes.push(mesh);
  31589. if (this.isReady()) {
  31590. this._applyToMesh(mesh);
  31591. }
  31592. else {
  31593. mesh._boundingInfo = this._boundingInfo;
  31594. }
  31595. };
  31596. Geometry.prototype.updateExtend = function (data) {
  31597. if (data === void 0) { data = null; }
  31598. if (!data) {
  31599. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31600. }
  31601. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  31602. };
  31603. Geometry.prototype._applyToMesh = function (mesh) {
  31604. var numOfMeshes = this._meshes.length;
  31605. // vertexBuffers
  31606. for (var kind in this._vertexBuffers) {
  31607. if (numOfMeshes === 1) {
  31608. this._vertexBuffers[kind].create();
  31609. }
  31610. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  31611. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31612. mesh._resetPointsArrayCache();
  31613. if (!this._extend) {
  31614. this.updateExtend(this._vertexBuffers[kind].getData());
  31615. }
  31616. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31617. mesh._createGlobalSubMesh();
  31618. //bounding info was just created again, world matrix should be applied again.
  31619. mesh._updateBoundingInfo();
  31620. }
  31621. }
  31622. // indexBuffer
  31623. if (numOfMeshes === 1 && this._indices) {
  31624. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31625. }
  31626. if (this._indexBuffer) {
  31627. this._indexBuffer.references = numOfMeshes;
  31628. }
  31629. };
  31630. Geometry.prototype.notifyUpdate = function (kind) {
  31631. if (this.onGeometryUpdated) {
  31632. this.onGeometryUpdated(this, kind);
  31633. }
  31634. };
  31635. Geometry.prototype.load = function (scene, onLoaded) {
  31636. var _this = this;
  31637. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31638. return;
  31639. }
  31640. if (this.isReady()) {
  31641. if (onLoaded) {
  31642. onLoaded();
  31643. }
  31644. return;
  31645. }
  31646. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31647. scene._addPendingData(this);
  31648. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31649. _this._delayLoadingFunction(JSON.parse(data), _this);
  31650. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31651. _this._delayInfo = [];
  31652. scene._removePendingData(_this);
  31653. var meshes = _this._meshes;
  31654. var numOfMeshes = meshes.length;
  31655. for (var index = 0; index < numOfMeshes; index++) {
  31656. _this._applyToMesh(meshes[index]);
  31657. }
  31658. if (onLoaded) {
  31659. onLoaded();
  31660. }
  31661. }, function () { }, scene.database);
  31662. };
  31663. Geometry.prototype.isDisposed = function () {
  31664. return this._isDisposed;
  31665. };
  31666. Geometry.prototype.dispose = function () {
  31667. var meshes = this._meshes;
  31668. var numOfMeshes = meshes.length;
  31669. var index;
  31670. for (index = 0; index < numOfMeshes; index++) {
  31671. this.releaseForMesh(meshes[index]);
  31672. }
  31673. this._meshes = [];
  31674. for (var kind in this._vertexBuffers) {
  31675. this._vertexBuffers[kind].dispose();
  31676. }
  31677. this._vertexBuffers = [];
  31678. this._totalVertices = 0;
  31679. if (this._indexBuffer) {
  31680. this._engine._releaseBuffer(this._indexBuffer);
  31681. }
  31682. this._indexBuffer = null;
  31683. this._indices = [];
  31684. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31685. this.delayLoadingFile = null;
  31686. this._delayLoadingFunction = null;
  31687. this._delayInfo = [];
  31688. this._boundingInfo = null;
  31689. this._scene.removeGeometry(this);
  31690. this._isDisposed = true;
  31691. };
  31692. Geometry.prototype.copy = function (id) {
  31693. var vertexData = new BABYLON.VertexData();
  31694. vertexData.indices = [];
  31695. var indices = this.getIndices();
  31696. for (var index = 0; index < indices.length; index++) {
  31697. vertexData.indices.push(indices[index]);
  31698. }
  31699. var updatable = false;
  31700. var stopChecking = false;
  31701. var kind;
  31702. for (kind in this._vertexBuffers) {
  31703. // using slice() to make a copy of the array and not just reference it
  31704. var data = this.getVerticesData(kind);
  31705. if (data instanceof Float32Array) {
  31706. vertexData.set(new Float32Array(data), kind);
  31707. }
  31708. else {
  31709. vertexData.set(data.slice(0), kind);
  31710. }
  31711. if (!stopChecking) {
  31712. updatable = this.getVertexBuffer(kind).isUpdatable();
  31713. stopChecking = !updatable;
  31714. }
  31715. }
  31716. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  31717. geometry.delayLoadState = this.delayLoadState;
  31718. geometry.delayLoadingFile = this.delayLoadingFile;
  31719. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31720. for (kind in this._delayInfo) {
  31721. geometry._delayInfo = geometry._delayInfo || [];
  31722. geometry._delayInfo.push(kind);
  31723. }
  31724. // Bounding info
  31725. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31726. return geometry;
  31727. };
  31728. Geometry.prototype.serialize = function () {
  31729. var serializationObject = {};
  31730. serializationObject.id = this.id;
  31731. if (BABYLON.Tags.HasTags(this)) {
  31732. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31733. }
  31734. return serializationObject;
  31735. };
  31736. Geometry.prototype.serializeVerticeData = function () {
  31737. var serializationObject = this.serialize();
  31738. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31739. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31740. }
  31741. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31742. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31743. }
  31744. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31745. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31746. }
  31747. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31748. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  31749. }
  31750. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31751. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  31752. }
  31753. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31754. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  31755. }
  31756. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31757. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  31758. }
  31759. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31760. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  31761. }
  31762. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31763. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31764. }
  31765. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31766. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31767. serializationObject.matricesIndices._isExpanded = true;
  31768. }
  31769. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31770. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31771. }
  31772. serializationObject.indices = this.getIndices();
  31773. return serializationObject;
  31774. };
  31775. // Statics
  31776. Geometry.ExtractFromMesh = function (mesh, id) {
  31777. var geometry = mesh._geometry;
  31778. if (!geometry) {
  31779. return null;
  31780. }
  31781. return geometry.copy(id);
  31782. };
  31783. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31784. // be aware Math.random() could cause collisions
  31785. Geometry.RandomId = function () {
  31786. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  31787. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  31788. return v.toString(16);
  31789. });
  31790. };
  31791. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31792. var scene = mesh.getScene();
  31793. // Geometry
  31794. var geometryId = parsedGeometry.geometryId;
  31795. if (geometryId) {
  31796. var geometry = scene.getGeometryByID(geometryId);
  31797. if (geometry) {
  31798. geometry.applyToMesh(mesh);
  31799. }
  31800. }
  31801. else if (parsedGeometry instanceof ArrayBuffer) {
  31802. var binaryInfo = mesh._binaryInfo;
  31803. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31804. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31805. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31806. }
  31807. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31808. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31809. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31810. }
  31811. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31812. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31813. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31814. }
  31815. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31816. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31817. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31818. }
  31819. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31820. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31821. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31822. }
  31823. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31824. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31825. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31826. }
  31827. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31828. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31829. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31830. }
  31831. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31832. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31833. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31834. }
  31835. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31836. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31837. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31838. }
  31839. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31840. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31841. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31842. }
  31843. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31844. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31845. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31846. }
  31847. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31848. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31849. mesh.setIndices(indicesData);
  31850. }
  31851. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31852. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31853. mesh.subMeshes = [];
  31854. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31855. var materialIndex = subMeshesData[(i * 5) + 0];
  31856. var verticesStart = subMeshesData[(i * 5) + 1];
  31857. var verticesCount = subMeshesData[(i * 5) + 2];
  31858. var indexStart = subMeshesData[(i * 5) + 3];
  31859. var indexCount = subMeshesData[(i * 5) + 4];
  31860. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31861. }
  31862. }
  31863. }
  31864. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31865. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  31866. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  31867. if (parsedGeometry.uvs) {
  31868. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  31869. }
  31870. if (parsedGeometry.uvs2) {
  31871. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  31872. }
  31873. if (parsedGeometry.uvs3) {
  31874. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  31875. }
  31876. if (parsedGeometry.uvs4) {
  31877. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  31878. }
  31879. if (parsedGeometry.uvs5) {
  31880. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  31881. }
  31882. if (parsedGeometry.uvs6) {
  31883. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  31884. }
  31885. if (parsedGeometry.colors) {
  31886. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  31887. }
  31888. if (parsedGeometry.matricesIndices) {
  31889. if (!parsedGeometry.matricesIndices._isExpanded) {
  31890. var floatIndices = [];
  31891. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31892. var matricesIndex = parsedGeometry.matricesIndices[i];
  31893. floatIndices.push(matricesIndex & 0x000000FF);
  31894. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31895. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31896. floatIndices.push(matricesIndex >> 24);
  31897. }
  31898. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  31899. }
  31900. else {
  31901. delete parsedGeometry.matricesIndices._isExpanded;
  31902. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  31903. }
  31904. }
  31905. if (parsedGeometry.matricesIndicesExtra) {
  31906. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31907. var floatIndices = [];
  31908. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31909. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31910. floatIndices.push(matricesIndex & 0x000000FF);
  31911. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31912. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31913. floatIndices.push(matricesIndex >> 24);
  31914. }
  31915. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  31916. }
  31917. else {
  31918. delete parsedGeometry.matricesIndices._isExpanded;
  31919. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  31920. }
  31921. }
  31922. if (parsedGeometry.matricesWeights) {
  31923. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  31924. }
  31925. if (parsedGeometry.matricesWeightsExtra) {
  31926. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  31927. }
  31928. mesh.setIndices(parsedGeometry.indices);
  31929. }
  31930. // SubMeshes
  31931. if (parsedGeometry.subMeshes) {
  31932. mesh.subMeshes = [];
  31933. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31934. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31935. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31936. }
  31937. }
  31938. // Flat shading
  31939. if (mesh._shouldGenerateFlatShading) {
  31940. mesh.convertToFlatShadedMesh();
  31941. delete mesh._shouldGenerateFlatShading;
  31942. }
  31943. // Update
  31944. mesh.computeWorldMatrix(true);
  31945. // Octree
  31946. if (scene['_selectionOctree']) {
  31947. scene['_selectionOctree'].addMesh(mesh);
  31948. }
  31949. };
  31950. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31951. if (scene.getGeometryByID(parsedVertexData.id)) {
  31952. return null; // null since geometry could be something else than a box...
  31953. }
  31954. var geometry = new Geometry(parsedVertexData.id, scene);
  31955. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31956. if (parsedVertexData.delayLoadingFile) {
  31957. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31958. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31959. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31960. geometry._delayInfo = [];
  31961. if (parsedVertexData.hasUVs) {
  31962. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31963. }
  31964. if (parsedVertexData.hasUVs2) {
  31965. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31966. }
  31967. if (parsedVertexData.hasUVs3) {
  31968. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31969. }
  31970. if (parsedVertexData.hasUVs4) {
  31971. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31972. }
  31973. if (parsedVertexData.hasUVs5) {
  31974. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31975. }
  31976. if (parsedVertexData.hasUVs6) {
  31977. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31978. }
  31979. if (parsedVertexData.hasColors) {
  31980. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31981. }
  31982. if (parsedVertexData.hasMatricesIndices) {
  31983. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31984. }
  31985. if (parsedVertexData.hasMatricesWeights) {
  31986. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31987. }
  31988. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31989. }
  31990. else {
  31991. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31992. }
  31993. scene.pushGeometry(geometry, true);
  31994. return geometry;
  31995. };
  31996. return Geometry;
  31997. })();
  31998. BABYLON.Geometry = Geometry;
  31999. /////// Primitives //////////////////////////////////////////////
  32000. var Geometry;
  32001. (function (Geometry) {
  32002. var Primitives;
  32003. (function (Primitives) {
  32004. /// Abstract class
  32005. var _Primitive = (function (_super) {
  32006. __extends(_Primitive, _super);
  32007. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  32008. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  32009. this._canBeRegenerated = _canBeRegenerated;
  32010. this._beingRegenerated = true;
  32011. this.regenerate();
  32012. this._beingRegenerated = false;
  32013. }
  32014. _Primitive.prototype.canBeRegenerated = function () {
  32015. return this._canBeRegenerated;
  32016. };
  32017. _Primitive.prototype.regenerate = function () {
  32018. if (!this._canBeRegenerated) {
  32019. return;
  32020. }
  32021. this._beingRegenerated = true;
  32022. this.setAllVerticesData(this._regenerateVertexData(), false);
  32023. this._beingRegenerated = false;
  32024. };
  32025. _Primitive.prototype.asNewGeometry = function (id) {
  32026. return _super.prototype.copy.call(this, id);
  32027. };
  32028. // overrides
  32029. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  32030. if (!this._beingRegenerated) {
  32031. return;
  32032. }
  32033. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32034. };
  32035. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  32036. if (!this._beingRegenerated) {
  32037. return;
  32038. }
  32039. _super.prototype.setVerticesData.call(this, kind, data, false);
  32040. };
  32041. // to override
  32042. // protected
  32043. _Primitive.prototype._regenerateVertexData = function () {
  32044. throw new Error("Abstract method");
  32045. };
  32046. _Primitive.prototype.copy = function (id) {
  32047. throw new Error("Must be overriden in sub-classes.");
  32048. };
  32049. _Primitive.prototype.serialize = function () {
  32050. var serializationObject = _super.prototype.serialize.call(this);
  32051. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32052. return serializationObject;
  32053. };
  32054. return _Primitive;
  32055. })(Geometry);
  32056. Primitives._Primitive = _Primitive;
  32057. var Ribbon = (function (_super) {
  32058. __extends(Ribbon, _super);
  32059. // Members
  32060. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32061. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32062. _super.call(this, id, scene, canBeRegenerated, mesh);
  32063. this.pathArray = pathArray;
  32064. this.closeArray = closeArray;
  32065. this.closePath = closePath;
  32066. this.offset = offset;
  32067. this.side = side;
  32068. }
  32069. Ribbon.prototype._regenerateVertexData = function () {
  32070. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32071. };
  32072. Ribbon.prototype.copy = function (id) {
  32073. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  32074. };
  32075. return Ribbon;
  32076. })(_Primitive);
  32077. Primitives.Ribbon = Ribbon;
  32078. var Box = (function (_super) {
  32079. __extends(Box, _super);
  32080. // Members
  32081. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32082. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32083. _super.call(this, id, scene, canBeRegenerated, mesh);
  32084. this.size = size;
  32085. this.side = side;
  32086. }
  32087. Box.prototype._regenerateVertexData = function () {
  32088. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32089. };
  32090. Box.prototype.copy = function (id) {
  32091. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32092. };
  32093. Box.prototype.serialize = function () {
  32094. var serializationObject = _super.prototype.serialize.call(this);
  32095. serializationObject.size = this.size;
  32096. return serializationObject;
  32097. };
  32098. Box.Parse = function (parsedBox, scene) {
  32099. if (scene.getGeometryByID(parsedBox.id)) {
  32100. return null; // null since geometry could be something else than a box...
  32101. }
  32102. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32103. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32104. scene.pushGeometry(box, true);
  32105. return box;
  32106. };
  32107. return Box;
  32108. })(_Primitive);
  32109. Primitives.Box = Box;
  32110. var Sphere = (function (_super) {
  32111. __extends(Sphere, _super);
  32112. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32113. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32114. _super.call(this, id, scene, canBeRegenerated, mesh);
  32115. this.segments = segments;
  32116. this.diameter = diameter;
  32117. this.side = side;
  32118. }
  32119. Sphere.prototype._regenerateVertexData = function () {
  32120. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32121. };
  32122. Sphere.prototype.copy = function (id) {
  32123. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32124. };
  32125. Sphere.prototype.serialize = function () {
  32126. var serializationObject = _super.prototype.serialize.call(this);
  32127. serializationObject.segments = this.segments;
  32128. serializationObject.diameter = this.diameter;
  32129. return serializationObject;
  32130. };
  32131. Sphere.Parse = function (parsedSphere, scene) {
  32132. if (scene.getGeometryByID(parsedSphere.id)) {
  32133. return null; // null since geometry could be something else than a sphere...
  32134. }
  32135. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32136. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32137. scene.pushGeometry(sphere, true);
  32138. return sphere;
  32139. };
  32140. return Sphere;
  32141. })(_Primitive);
  32142. Primitives.Sphere = Sphere;
  32143. var Disc = (function (_super) {
  32144. __extends(Disc, _super);
  32145. // Members
  32146. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32147. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32148. _super.call(this, id, scene, canBeRegenerated, mesh);
  32149. this.radius = radius;
  32150. this.tessellation = tessellation;
  32151. this.side = side;
  32152. }
  32153. Disc.prototype._regenerateVertexData = function () {
  32154. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32155. };
  32156. Disc.prototype.copy = function (id) {
  32157. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32158. };
  32159. return Disc;
  32160. })(_Primitive);
  32161. Primitives.Disc = Disc;
  32162. var Cylinder = (function (_super) {
  32163. __extends(Cylinder, _super);
  32164. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32165. if (subdivisions === void 0) { subdivisions = 1; }
  32166. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32167. _super.call(this, id, scene, canBeRegenerated, mesh);
  32168. this.height = height;
  32169. this.diameterTop = diameterTop;
  32170. this.diameterBottom = diameterBottom;
  32171. this.tessellation = tessellation;
  32172. this.subdivisions = subdivisions;
  32173. this.side = side;
  32174. }
  32175. Cylinder.prototype._regenerateVertexData = function () {
  32176. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32177. };
  32178. Cylinder.prototype.copy = function (id) {
  32179. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32180. };
  32181. Cylinder.prototype.serialize = function () {
  32182. var serializationObject = _super.prototype.serialize.call(this);
  32183. serializationObject.height = this.height;
  32184. serializationObject.diameterTop = this.diameterTop;
  32185. serializationObject.diameterBottom = this.diameterBottom;
  32186. serializationObject.tessellation = this.tessellation;
  32187. return serializationObject;
  32188. };
  32189. Cylinder.Parse = function (parsedCylinder, scene) {
  32190. if (scene.getGeometryByID(parsedCylinder.id)) {
  32191. return null; // null since geometry could be something else than a cylinder...
  32192. }
  32193. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32194. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32195. scene.pushGeometry(cylinder, true);
  32196. return cylinder;
  32197. };
  32198. return Cylinder;
  32199. })(_Primitive);
  32200. Primitives.Cylinder = Cylinder;
  32201. var Torus = (function (_super) {
  32202. __extends(Torus, _super);
  32203. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32204. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32205. _super.call(this, id, scene, canBeRegenerated, mesh);
  32206. this.diameter = diameter;
  32207. this.thickness = thickness;
  32208. this.tessellation = tessellation;
  32209. this.side = side;
  32210. }
  32211. Torus.prototype._regenerateVertexData = function () {
  32212. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32213. };
  32214. Torus.prototype.copy = function (id) {
  32215. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32216. };
  32217. Torus.prototype.serialize = function () {
  32218. var serializationObject = _super.prototype.serialize.call(this);
  32219. serializationObject.diameter = this.diameter;
  32220. serializationObject.thickness = this.thickness;
  32221. serializationObject.tessellation = this.tessellation;
  32222. return serializationObject;
  32223. };
  32224. Torus.Parse = function (parsedTorus, scene) {
  32225. if (scene.getGeometryByID(parsedTorus.id)) {
  32226. return null; // null since geometry could be something else than a torus...
  32227. }
  32228. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32229. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32230. scene.pushGeometry(torus, true);
  32231. return torus;
  32232. };
  32233. return Torus;
  32234. })(_Primitive);
  32235. Primitives.Torus = Torus;
  32236. var Ground = (function (_super) {
  32237. __extends(Ground, _super);
  32238. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32239. _super.call(this, id, scene, canBeRegenerated, mesh);
  32240. this.width = width;
  32241. this.height = height;
  32242. this.subdivisions = subdivisions;
  32243. }
  32244. Ground.prototype._regenerateVertexData = function () {
  32245. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32246. };
  32247. Ground.prototype.copy = function (id) {
  32248. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32249. };
  32250. Ground.prototype.serialize = function () {
  32251. var serializationObject = _super.prototype.serialize.call(this);
  32252. serializationObject.width = this.width;
  32253. serializationObject.height = this.height;
  32254. serializationObject.subdivisions = this.subdivisions;
  32255. return serializationObject;
  32256. };
  32257. Ground.Parse = function (parsedGround, scene) {
  32258. if (scene.getGeometryByID(parsedGround.id)) {
  32259. return null; // null since geometry could be something else than a ground...
  32260. }
  32261. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32262. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32263. scene.pushGeometry(ground, true);
  32264. return ground;
  32265. };
  32266. return Ground;
  32267. })(_Primitive);
  32268. Primitives.Ground = Ground;
  32269. var TiledGround = (function (_super) {
  32270. __extends(TiledGround, _super);
  32271. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32272. _super.call(this, id, scene, canBeRegenerated, mesh);
  32273. this.xmin = xmin;
  32274. this.zmin = zmin;
  32275. this.xmax = xmax;
  32276. this.zmax = zmax;
  32277. this.subdivisions = subdivisions;
  32278. this.precision = precision;
  32279. }
  32280. TiledGround.prototype._regenerateVertexData = function () {
  32281. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32282. };
  32283. TiledGround.prototype.copy = function (id) {
  32284. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32285. };
  32286. return TiledGround;
  32287. })(_Primitive);
  32288. Primitives.TiledGround = TiledGround;
  32289. var Plane = (function (_super) {
  32290. __extends(Plane, _super);
  32291. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32292. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32293. _super.call(this, id, scene, canBeRegenerated, mesh);
  32294. this.size = size;
  32295. this.side = side;
  32296. }
  32297. Plane.prototype._regenerateVertexData = function () {
  32298. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32299. };
  32300. Plane.prototype.copy = function (id) {
  32301. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32302. };
  32303. Plane.prototype.serialize = function () {
  32304. var serializationObject = _super.prototype.serialize.call(this);
  32305. serializationObject.size = this.size;
  32306. return serializationObject;
  32307. };
  32308. Plane.Parse = function (parsedPlane, scene) {
  32309. if (scene.getGeometryByID(parsedPlane.id)) {
  32310. return null; // null since geometry could be something else than a ground...
  32311. }
  32312. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32313. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32314. scene.pushGeometry(plane, true);
  32315. return plane;
  32316. };
  32317. return Plane;
  32318. })(_Primitive);
  32319. Primitives.Plane = Plane;
  32320. var TorusKnot = (function (_super) {
  32321. __extends(TorusKnot, _super);
  32322. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32323. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32324. _super.call(this, id, scene, canBeRegenerated, mesh);
  32325. this.radius = radius;
  32326. this.tube = tube;
  32327. this.radialSegments = radialSegments;
  32328. this.tubularSegments = tubularSegments;
  32329. this.p = p;
  32330. this.q = q;
  32331. this.side = side;
  32332. }
  32333. TorusKnot.prototype._regenerateVertexData = function () {
  32334. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  32335. };
  32336. TorusKnot.prototype.copy = function (id) {
  32337. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32338. };
  32339. TorusKnot.prototype.serialize = function () {
  32340. var serializationObject = _super.prototype.serialize.call(this);
  32341. serializationObject.radius = this.radius;
  32342. serializationObject.tube = this.tube;
  32343. serializationObject.radialSegments = this.radialSegments;
  32344. serializationObject.tubularSegments = this.tubularSegments;
  32345. serializationObject.p = this.p;
  32346. serializationObject.q = this.q;
  32347. return serializationObject;
  32348. };
  32349. ;
  32350. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32351. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32352. return null; // null since geometry could be something else than a ground...
  32353. }
  32354. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32355. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32356. scene.pushGeometry(torusKnot, true);
  32357. return torusKnot;
  32358. };
  32359. return TorusKnot;
  32360. })(_Primitive);
  32361. Primitives.TorusKnot = TorusKnot;
  32362. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32363. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32364. })(BABYLON || (BABYLON = {}));
  32365. var BABYLON;
  32366. (function (BABYLON) {
  32367. var GroundMesh = (function (_super) {
  32368. __extends(GroundMesh, _super);
  32369. function GroundMesh(name, scene) {
  32370. _super.call(this, name, scene);
  32371. this.generateOctree = false;
  32372. this._worldInverse = new BABYLON.Matrix();
  32373. }
  32374. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  32375. get: function () {
  32376. return this._subdivisions;
  32377. },
  32378. enumerable: true,
  32379. configurable: true
  32380. });
  32381. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  32382. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  32383. this._subdivisions = chunksCount;
  32384. this.subdivide(this._subdivisions);
  32385. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  32386. };
  32387. /**
  32388. * Returns a height (y) value in the Worl system :
  32389. * the ground altitude at the coordinates (x, z) expressed in the World system.
  32390. * Returns the ground y position if (x, z) are outside the ground surface.
  32391. * Not pertinent if the ground is rotated.
  32392. */
  32393. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  32394. // express x and y in the ground local system
  32395. x -= this.position.x;
  32396. z -= this.position.z;
  32397. x /= this.scaling.x;
  32398. z /= this.scaling.z;
  32399. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  32400. return this.position.y;
  32401. }
  32402. if (!this._heightQuads || this._heightQuads.length == 0) {
  32403. this._initHeightQuads();
  32404. this._computeHeightQuads();
  32405. }
  32406. var facet = this._getFacetAt(x, z);
  32407. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  32408. // return y in the World system
  32409. return y * this.scaling.y + this.position.y;
  32410. };
  32411. /**
  32412. * Returns a normalized vector (Vector3) orthogonal to the ground
  32413. * at the ground coordinates (x, z) expressed in the World system.
  32414. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  32415. * Not pertinent if the ground is rotated.
  32416. */
  32417. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  32418. var normal = new BABYLON.Vector3(0, 1, 0);
  32419. this.getNormalAtCoordinatesToRef(x, z, normal);
  32420. return normal;
  32421. };
  32422. /**
  32423. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  32424. * at the ground coordinates (x, z) expressed in the World system.
  32425. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  32426. * Not pertinent if the ground is rotated.
  32427. */
  32428. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  32429. // express x and y in the ground local system
  32430. x -= this.position.x;
  32431. z -= this.position.z;
  32432. x /= this.scaling.x;
  32433. z /= this.scaling.z;
  32434. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  32435. return;
  32436. }
  32437. if (!this._heightQuads || this._heightQuads.length == 0) {
  32438. this._initHeightQuads();
  32439. this._computeHeightQuads();
  32440. }
  32441. var facet = this._getFacetAt(x, z);
  32442. ref.x = facet.x;
  32443. ref.y = facet.y;
  32444. ref.z = facet.z;
  32445. };
  32446. /**
  32447. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  32448. * if the ground has been updated.
  32449. * This can be used in the render loop
  32450. */
  32451. GroundMesh.prototype.updateCoordinateHeights = function () {
  32452. if (!this._heightQuads || this._heightQuads.length == 0) {
  32453. this._initHeightQuads();
  32454. }
  32455. this._computeHeightQuads();
  32456. };
  32457. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  32458. GroundMesh.prototype._getFacetAt = function (x, z) {
  32459. // retrieve col and row from x, z coordinates in the ground local system
  32460. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  32461. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  32462. var quad = this._heightQuads[row * this._subdivisions + col];
  32463. var facet;
  32464. if (z < quad.slope.x * x + quad.slope.y) {
  32465. facet = quad.facet1;
  32466. }
  32467. else {
  32468. facet = quad.facet2;
  32469. }
  32470. return facet;
  32471. };
  32472. // Creates and populates the heightMap array with "facet" elements :
  32473. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  32474. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32475. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32476. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32477. GroundMesh.prototype._initHeightQuads = function () {
  32478. this._heightQuads = new Array();
  32479. for (var row = 0; row < this._subdivisions; row++) {
  32480. for (var col = 0; col < this._subdivisions; col++) {
  32481. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  32482. this._heightQuads[row * this._subdivisions + col] = quad;
  32483. }
  32484. }
  32485. };
  32486. // Compute each quad element values and update the the heightMap array :
  32487. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32488. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32489. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32490. GroundMesh.prototype._computeHeightQuads = function () {
  32491. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32492. var v1 = BABYLON.Tmp.Vector3[0];
  32493. var v2 = BABYLON.Tmp.Vector3[1];
  32494. var v3 = BABYLON.Tmp.Vector3[2];
  32495. var v4 = BABYLON.Tmp.Vector3[3];
  32496. var v1v2 = BABYLON.Tmp.Vector3[4];
  32497. var v1v3 = BABYLON.Tmp.Vector3[5];
  32498. var v1v4 = BABYLON.Tmp.Vector3[6];
  32499. var norm1 = BABYLON.Tmp.Vector3[7];
  32500. var norm2 = BABYLON.Tmp.Vector3[8];
  32501. var i = 0;
  32502. var j = 0;
  32503. var k = 0;
  32504. var cd = 0; // 2D slope coefficient : z = cd * x + h
  32505. var h = 0;
  32506. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  32507. var d2 = 0;
  32508. for (var row = 0; row < this._subdivisions; row++) {
  32509. for (var col = 0; col < this._subdivisions; col++) {
  32510. i = col * 3;
  32511. j = row * (this._subdivisions + 1) * 3;
  32512. k = (row + 1) * (this._subdivisions + 1) * 3;
  32513. v1.x = positions[j + i];
  32514. v1.y = positions[j + i + 1];
  32515. v1.z = positions[j + i + 2];
  32516. v2.x = positions[j + i + 3];
  32517. v2.y = positions[j + i + 4];
  32518. v2.z = positions[j + i + 5];
  32519. v3.x = positions[k + i];
  32520. v3.y = positions[k + i + 1];
  32521. v3.z = positions[k + i + 2];
  32522. v4.x = positions[k + i + 3];
  32523. v4.y = positions[k + i + 4];
  32524. v4.z = positions[k + i + 5];
  32525. // 2D slope V1V4
  32526. cd = (v4.z - v1.z) / (v4.x - v1.x);
  32527. h = v1.z - cd * v1.x; // v1 belongs to the slope
  32528. // facet equations :
  32529. // we compute each facet normal vector
  32530. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  32531. // we compute the value d by applying the equation to v1 which belongs to the plane
  32532. // then we store the facet equation in a Vector4
  32533. v2.subtractToRef(v1, v1v2);
  32534. v3.subtractToRef(v1, v1v3);
  32535. v4.subtractToRef(v1, v1v4);
  32536. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  32537. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  32538. norm1.normalize();
  32539. norm2.normalize();
  32540. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  32541. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  32542. var quad = this._heightQuads[row * this._subdivisions + col];
  32543. quad.slope.copyFromFloats(cd, h);
  32544. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  32545. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  32546. }
  32547. }
  32548. };
  32549. return GroundMesh;
  32550. })(BABYLON.Mesh);
  32551. BABYLON.GroundMesh = GroundMesh;
  32552. })(BABYLON || (BABYLON = {}));
  32553. var BABYLON;
  32554. (function (BABYLON) {
  32555. var LinesMesh = (function (_super) {
  32556. __extends(LinesMesh, _super);
  32557. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  32558. if (parent === void 0) { parent = null; }
  32559. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  32560. this.color = new BABYLON.Color3(1, 1, 1);
  32561. this.alpha = 1;
  32562. if (source) {
  32563. this.color = source.color.clone();
  32564. this.alpha = source.alpha;
  32565. }
  32566. this._intersectionThreshold = 0.1;
  32567. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  32568. attributes: ["position"],
  32569. uniforms: ["worldViewProjection", "color"],
  32570. needAlphaBlending: true
  32571. });
  32572. }
  32573. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  32574. /**
  32575. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32576. * This margin is expressed in world space coordinates, so its value may vary.
  32577. * Default value is 0.1
  32578. * @returns the intersection Threshold value.
  32579. */
  32580. get: function () {
  32581. return this._intersectionThreshold;
  32582. },
  32583. /**
  32584. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32585. * This margin is expressed in world space coordinates, so its value may vary.
  32586. * @param value the new threshold to apply
  32587. */
  32588. set: function (value) {
  32589. if (this._intersectionThreshold === value) {
  32590. return;
  32591. }
  32592. this._intersectionThreshold = value;
  32593. if (this.geometry) {
  32594. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  32595. }
  32596. },
  32597. enumerable: true,
  32598. configurable: true
  32599. });
  32600. Object.defineProperty(LinesMesh.prototype, "material", {
  32601. get: function () {
  32602. return this._colorShader;
  32603. },
  32604. enumerable: true,
  32605. configurable: true
  32606. });
  32607. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  32608. get: function () {
  32609. return false;
  32610. },
  32611. enumerable: true,
  32612. configurable: true
  32613. });
  32614. LinesMesh.prototype.createInstance = function (name) {
  32615. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  32616. return null;
  32617. };
  32618. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  32619. var engine = this.getScene().getEngine();
  32620. var indexToBind = this._geometry.getIndexBuffer();
  32621. // VBOs
  32622. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  32623. // Color
  32624. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  32625. };
  32626. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  32627. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  32628. return;
  32629. }
  32630. var engine = this.getScene().getEngine();
  32631. // Draw order
  32632. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  32633. };
  32634. LinesMesh.prototype.dispose = function (doNotRecurse) {
  32635. this._colorShader.dispose();
  32636. _super.prototype.dispose.call(this, doNotRecurse);
  32637. };
  32638. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  32639. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  32640. };
  32641. return LinesMesh;
  32642. })(BABYLON.Mesh);
  32643. BABYLON.LinesMesh = LinesMesh;
  32644. })(BABYLON || (BABYLON = {}));
  32645. var BABYLON;
  32646. (function (BABYLON) {
  32647. var DebugLayer = (function () {
  32648. function DebugLayer(scene) {
  32649. var _this = this;
  32650. this._transformationMatrix = BABYLON.Matrix.Identity();
  32651. this._enabled = false;
  32652. this._labelsEnabled = false;
  32653. this._displayStatistics = true;
  32654. this._displayTree = false;
  32655. this._displayLogs = false;
  32656. this._skeletonViewers = new Array();
  32657. this._identityMatrix = BABYLON.Matrix.Identity();
  32658. this.axisRatio = 0.02;
  32659. this.accentColor = "orange";
  32660. this._scene = scene;
  32661. this._syncPositions = function () {
  32662. var engine = _this._scene.getEngine();
  32663. var canvasRect = engine.getRenderingCanvasClientRect();
  32664. if (_this._showUI) {
  32665. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  32666. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  32667. _this._statsDiv.style.width = "400px";
  32668. _this._statsDiv.style.height = "auto";
  32669. _this._statsSubsetDiv.style.maxHeight = "240px";
  32670. _this._optionsDiv.style.left = "0px";
  32671. _this._optionsDiv.style.top = "10px";
  32672. _this._optionsDiv.style.width = "200px";
  32673. _this._optionsDiv.style.height = "auto";
  32674. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  32675. _this._logDiv.style.left = "0px";
  32676. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  32677. _this._logDiv.style.width = "600px";
  32678. _this._logDiv.style.height = "160px";
  32679. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  32680. _this._treeDiv.style.top = "10px";
  32681. _this._treeDiv.style.width = "300px";
  32682. _this._treeDiv.style.height = "auto";
  32683. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  32684. }
  32685. _this._globalDiv.style.left = canvasRect.left + "px";
  32686. _this._globalDiv.style.top = canvasRect.top + "px";
  32687. _this._drawingCanvas.style.left = "0px";
  32688. _this._drawingCanvas.style.top = "0px";
  32689. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  32690. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  32691. var devicePixelRatio = window.devicePixelRatio || 1;
  32692. var context = _this._drawingContext;
  32693. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  32694. context.mozBackingStorePixelRatio ||
  32695. context.msBackingStorePixelRatio ||
  32696. context.oBackingStorePixelRatio ||
  32697. context.backingStorePixelRatio || 1;
  32698. _this._ratio = devicePixelRatio / backingStoreRatio;
  32699. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  32700. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  32701. };
  32702. this._onCanvasClick = function (evt) {
  32703. _this._clickPosition = {
  32704. x: evt.clientX * _this._ratio,
  32705. y: evt.clientY * _this._ratio
  32706. };
  32707. };
  32708. this._syncUI = function () {
  32709. if (_this._showUI) {
  32710. if (_this._displayStatistics) {
  32711. _this._displayStats();
  32712. _this._statsDiv.style.display = "";
  32713. }
  32714. else {
  32715. _this._statsDiv.style.display = "none";
  32716. }
  32717. if (_this._displayLogs) {
  32718. _this._logDiv.style.display = "";
  32719. }
  32720. else {
  32721. _this._logDiv.style.display = "none";
  32722. }
  32723. if (_this._displayTree) {
  32724. _this._treeDiv.style.display = "";
  32725. if (_this._needToRefreshMeshesTree) {
  32726. _this._needToRefreshMeshesTree = false;
  32727. _this._refreshMeshesTreeContent();
  32728. }
  32729. }
  32730. else {
  32731. _this._treeDiv.style.display = "none";
  32732. }
  32733. }
  32734. };
  32735. this._syncData = function () {
  32736. if (_this._labelsEnabled || !_this._showUI) {
  32737. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  32738. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  32739. var engine = _this._scene.getEngine();
  32740. var viewport = _this._camera.viewport;
  32741. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  32742. // Meshes
  32743. var meshes = _this._camera.getActiveMeshes();
  32744. var index;
  32745. var projectedPosition;
  32746. for (index = 0; index < meshes.length; index++) {
  32747. var mesh = meshes.data[index];
  32748. var position = mesh.getBoundingInfo().boundingSphere.center;
  32749. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32750. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  32751. _this._renderAxis(projectedPosition, mesh, globalViewport);
  32752. }
  32753. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  32754. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  32755. }
  32756. }
  32757. // Cameras
  32758. var cameras = _this._scene.cameras;
  32759. for (index = 0; index < cameras.length; index++) {
  32760. var camera = cameras[index];
  32761. if (camera === _this._camera) {
  32762. continue;
  32763. }
  32764. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32765. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  32766. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  32767. _this._camera.detachControl(engine.getRenderingCanvas());
  32768. _this._camera = camera;
  32769. _this._camera.attachControl(engine.getRenderingCanvas());
  32770. }, function () { return "purple"; });
  32771. }
  32772. }
  32773. // Lights
  32774. var lights = _this._scene.lights;
  32775. for (index = 0; index < lights.length; index++) {
  32776. var light = lights[index];
  32777. if (light.position) {
  32778. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  32779. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  32780. _this._renderLabel(light.name, projectedPosition, -20, function () {
  32781. light.setEnabled(!light.isEnabled());
  32782. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  32783. }
  32784. }
  32785. }
  32786. }
  32787. _this._clickPosition = undefined;
  32788. };
  32789. }
  32790. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  32791. while (this._treeSubsetDiv.hasChildNodes()) {
  32792. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  32793. }
  32794. // Add meshes
  32795. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  32796. sortedArray.sort(function (a, b) {
  32797. if (a.name === b.name) {
  32798. return 0;
  32799. }
  32800. return (a.name > b.name) ? 1 : -1;
  32801. });
  32802. for (var index = 0; index < sortedArray.length; index++) {
  32803. var mesh = sortedArray[index];
  32804. if (!mesh.isEnabled()) {
  32805. continue;
  32806. }
  32807. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  32808. m.isVisible = element.checked;
  32809. }, mesh);
  32810. }
  32811. };
  32812. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  32813. this._drawingContext.beginPath();
  32814. this._drawingContext.moveTo(zero.x, zero.y);
  32815. this._drawingContext.lineTo(unit.x, unit.y);
  32816. this._drawingContext.strokeStyle = color;
  32817. this._drawingContext.lineWidth = 4;
  32818. this._drawingContext.stroke();
  32819. this._drawingContext.font = "normal 14px Segoe UI";
  32820. this._drawingContext.fillStyle = color;
  32821. this._drawingContext.fillText(label, unitText.x, unitText.y);
  32822. };
  32823. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  32824. var position = mesh.getBoundingInfo().boundingSphere.center;
  32825. var worldMatrix = mesh.getWorldMatrix();
  32826. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  32827. var unit = (unprojectedVector.subtract(position)).length();
  32828. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32829. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32830. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  32831. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32832. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32833. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  32834. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  32835. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  32836. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  32837. };
  32838. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  32839. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  32840. this._drawingContext.font = "normal 12px Segoe UI";
  32841. var textMetrics = this._drawingContext.measureText(text);
  32842. var centerX = projectedPosition.x - textMetrics.width / 2;
  32843. var centerY = projectedPosition.y;
  32844. var clientRect = this._drawingCanvas.getBoundingClientRect();
  32845. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  32846. onClick();
  32847. }
  32848. this._drawingContext.beginPath();
  32849. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  32850. this._drawingContext.fillStyle = getFillStyle();
  32851. this._drawingContext.globalAlpha = 0.5;
  32852. this._drawingContext.fill();
  32853. this._drawingContext.globalAlpha = 1.0;
  32854. this._drawingContext.strokeStyle = '#FFFFFF';
  32855. this._drawingContext.lineWidth = 1;
  32856. this._drawingContext.stroke();
  32857. this._drawingContext.fillStyle = "#FFFFFF";
  32858. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  32859. this._drawingContext.beginPath();
  32860. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  32861. this._drawingContext.fill();
  32862. }
  32863. };
  32864. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  32865. if (!this._clickPosition) {
  32866. return false;
  32867. }
  32868. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  32869. return false;
  32870. }
  32871. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  32872. return false;
  32873. }
  32874. return true;
  32875. };
  32876. DebugLayer.prototype.isVisible = function () {
  32877. return this._enabled;
  32878. };
  32879. DebugLayer.prototype.hide = function () {
  32880. if (!this._enabled) {
  32881. return;
  32882. }
  32883. this._enabled = false;
  32884. var engine = this._scene.getEngine();
  32885. this._scene.unregisterBeforeRender(this._syncData);
  32886. this._scene.unregisterAfterRender(this._syncUI);
  32887. this._rootElement.removeChild(this._globalDiv);
  32888. this._scene.forceShowBoundingBoxes = false;
  32889. this._scene.forceWireframe = false;
  32890. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  32891. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  32892. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  32893. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  32894. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  32895. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  32896. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  32897. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  32898. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  32899. this._scene.shadowsEnabled = true;
  32900. this._scene.particlesEnabled = true;
  32901. this._scene.postProcessesEnabled = true;
  32902. this._scene.collisionsEnabled = true;
  32903. this._scene.lightsEnabled = true;
  32904. this._scene.texturesEnabled = true;
  32905. this._scene.lensFlaresEnabled = true;
  32906. this._scene.proceduralTexturesEnabled = true;
  32907. this._scene.renderTargetsEnabled = true;
  32908. this._scene.probesEnabled = true;
  32909. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  32910. this._clearSkeletonViewers();
  32911. };
  32912. DebugLayer.prototype._clearSkeletonViewers = function () {
  32913. for (var index = 0; index < this._skeletonViewers.length; index++) {
  32914. this._skeletonViewers[index].dispose();
  32915. }
  32916. this._skeletonViewers = [];
  32917. };
  32918. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  32919. if (showUI === void 0) { showUI = true; }
  32920. if (camera === void 0) { camera = null; }
  32921. if (rootElement === void 0) { rootElement = null; }
  32922. if (this._enabled) {
  32923. return;
  32924. }
  32925. this._enabled = true;
  32926. if (camera) {
  32927. this._camera = camera;
  32928. }
  32929. else {
  32930. this._camera = this._scene.activeCamera;
  32931. }
  32932. this._showUI = showUI;
  32933. var engine = this._scene.getEngine();
  32934. this._globalDiv = document.createElement("div");
  32935. this._rootElement = rootElement || document.body;
  32936. this._rootElement.appendChild(this._globalDiv);
  32937. this._generateDOMelements();
  32938. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  32939. this._syncPositions();
  32940. this._scene.registerBeforeRender(this._syncData);
  32941. this._scene.registerAfterRender(this._syncUI);
  32942. };
  32943. DebugLayer.prototype._clearLabels = function () {
  32944. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  32945. for (var index = 0; index < this._scene.meshes.length; index++) {
  32946. var mesh = this._scene.meshes[index];
  32947. mesh.renderOverlay = false;
  32948. }
  32949. };
  32950. DebugLayer.prototype._generateheader = function (root, text) {
  32951. var header = document.createElement("div");
  32952. header.innerHTML = text + "&nbsp;";
  32953. header.style.textAlign = "right";
  32954. header.style.width = "100%";
  32955. header.style.color = "white";
  32956. header.style.backgroundColor = "Black";
  32957. header.style.padding = "5px 5px 4px 0px";
  32958. header.style.marginLeft = "-5px";
  32959. header.style.fontWeight = "bold";
  32960. root.appendChild(header);
  32961. };
  32962. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  32963. var label = document.createElement("label");
  32964. label.style.display = "inline";
  32965. label.innerHTML = title;
  32966. label.style.color = color;
  32967. root.appendChild(label);
  32968. root.appendChild(document.createElement("br"));
  32969. };
  32970. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  32971. if (tag === void 0) { tag = null; }
  32972. var label = document.createElement("label");
  32973. label.style.display = "inline";
  32974. var boundingBoxesCheckbox = document.createElement("input");
  32975. boundingBoxesCheckbox.type = "checkbox";
  32976. boundingBoxesCheckbox.checked = initialState;
  32977. boundingBoxesCheckbox.style.display = "inline";
  32978. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  32979. boundingBoxesCheckbox.style.verticalAlign = "sub";
  32980. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  32981. task(evt.target, tag);
  32982. });
  32983. label.appendChild(boundingBoxesCheckbox);
  32984. var container = document.createElement("span");
  32985. var leftPart = document.createElement("span");
  32986. var rightPart = document.createElement("span");
  32987. rightPart.style.cssFloat = "right";
  32988. leftPart.innerHTML = leftTitle;
  32989. rightPart.innerHTML = rightTitle;
  32990. rightPart.style.fontSize = "12px";
  32991. rightPart.style.maxWidth = "200px";
  32992. container.appendChild(leftPart);
  32993. container.appendChild(rightPart);
  32994. label.appendChild(container);
  32995. root.appendChild(label);
  32996. root.appendChild(document.createElement("br"));
  32997. };
  32998. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  32999. if (tag === void 0) { tag = null; }
  33000. var label = document.createElement("label");
  33001. label.style.display = "inline";
  33002. var checkBox = document.createElement("input");
  33003. checkBox.type = "checkbox";
  33004. checkBox.checked = initialState;
  33005. checkBox.style.display = "inline";
  33006. checkBox.style.margin = "0px 5px 0px 0px";
  33007. checkBox.style.verticalAlign = "sub";
  33008. checkBox.addEventListener("change", function (evt) {
  33009. task(evt.target, tag);
  33010. });
  33011. label.appendChild(checkBox);
  33012. label.appendChild(document.createTextNode(title));
  33013. root.appendChild(label);
  33014. root.appendChild(document.createElement("br"));
  33015. };
  33016. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  33017. if (tag === void 0) { tag = null; }
  33018. var button = document.createElement("button");
  33019. button.innerHTML = title;
  33020. button.style.height = "24px";
  33021. button.style.width = "150px";
  33022. button.style.marginBottom = "5px";
  33023. button.style.color = "#444444";
  33024. button.style.border = "1px solid white";
  33025. button.className = "debugLayerButton";
  33026. button.addEventListener("click", function (evt) {
  33027. task(evt.target, tag);
  33028. });
  33029. root.appendChild(button);
  33030. root.appendChild(document.createElement("br"));
  33031. };
  33032. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  33033. if (tag === void 0) { tag = null; }
  33034. var label = document.createElement("label");
  33035. label.style.display = "inline";
  33036. var boundingBoxesRadio = document.createElement("input");
  33037. boundingBoxesRadio.type = "radio";
  33038. boundingBoxesRadio.name = name;
  33039. boundingBoxesRadio.checked = initialState;
  33040. boundingBoxesRadio.style.display = "inline";
  33041. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  33042. boundingBoxesRadio.style.verticalAlign = "sub";
  33043. boundingBoxesRadio.addEventListener("change", function (evt) {
  33044. task(evt.target, tag);
  33045. });
  33046. label.appendChild(boundingBoxesRadio);
  33047. label.appendChild(document.createTextNode(title));
  33048. root.appendChild(label);
  33049. root.appendChild(document.createElement("br"));
  33050. };
  33051. DebugLayer.prototype._generateDOMelements = function () {
  33052. var _this = this;
  33053. this._globalDiv.id = "DebugLayer";
  33054. this._globalDiv.style.position = "absolute";
  33055. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  33056. this._globalDiv.style.fontSize = "14px";
  33057. this._globalDiv.style.color = "white";
  33058. // Drawing canvas
  33059. this._drawingCanvas = document.createElement("canvas");
  33060. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  33061. this._drawingCanvas.style.position = "absolute";
  33062. this._drawingCanvas.style.pointerEvents = "none";
  33063. this._drawingCanvas.style.backgroundColor = "transparent";
  33064. this._drawingContext = this._drawingCanvas.getContext("2d");
  33065. this._globalDiv.appendChild(this._drawingCanvas);
  33066. if (this._showUI) {
  33067. var background = "rgba(128, 128, 128, 0.4)";
  33068. var border = "rgb(180, 180, 180) solid 1px";
  33069. // Stats
  33070. this._statsDiv = document.createElement("div");
  33071. this._statsDiv.id = "DebugLayerStats";
  33072. this._statsDiv.style.border = border;
  33073. this._statsDiv.style.position = "absolute";
  33074. this._statsDiv.style.background = background;
  33075. this._statsDiv.style.padding = "0px 0px 0px 5px";
  33076. this._generateheader(this._statsDiv, "STATISTICS");
  33077. this._statsSubsetDiv = document.createElement("div");
  33078. this._statsSubsetDiv.style.paddingTop = "5px";
  33079. this._statsSubsetDiv.style.paddingBottom = "5px";
  33080. this._statsSubsetDiv.style.overflowY = "auto";
  33081. this._statsDiv.appendChild(this._statsSubsetDiv);
  33082. // Tree
  33083. this._treeDiv = document.createElement("div");
  33084. this._treeDiv.id = "DebugLayerTree";
  33085. this._treeDiv.style.border = border;
  33086. this._treeDiv.style.position = "absolute";
  33087. this._treeDiv.style.background = background;
  33088. this._treeDiv.style.padding = "0px 0px 0px 5px";
  33089. this._treeDiv.style.display = "none";
  33090. this._generateheader(this._treeDiv, "MESHES TREE");
  33091. this._treeSubsetDiv = document.createElement("div");
  33092. this._treeSubsetDiv.style.paddingTop = "5px";
  33093. this._treeSubsetDiv.style.paddingRight = "5px";
  33094. this._treeSubsetDiv.style.overflowY = "auto";
  33095. this._treeSubsetDiv.style.maxHeight = "300px";
  33096. this._treeDiv.appendChild(this._treeSubsetDiv);
  33097. this._needToRefreshMeshesTree = true;
  33098. // Logs
  33099. this._logDiv = document.createElement("div");
  33100. this._logDiv.style.border = border;
  33101. this._logDiv.id = "DebugLayerLogs";
  33102. this._logDiv.style.position = "absolute";
  33103. this._logDiv.style.background = background;
  33104. this._logDiv.style.padding = "0px 0px 0px 5px";
  33105. this._logDiv.style.display = "none";
  33106. this._generateheader(this._logDiv, "LOGS");
  33107. this._logSubsetDiv = document.createElement("div");
  33108. this._logSubsetDiv.style.height = "127px";
  33109. this._logSubsetDiv.style.paddingTop = "5px";
  33110. this._logSubsetDiv.style.overflowY = "auto";
  33111. this._logSubsetDiv.style.fontSize = "12px";
  33112. this._logSubsetDiv.style.fontFamily = "consolas";
  33113. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  33114. this._logDiv.appendChild(this._logSubsetDiv);
  33115. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  33116. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  33117. };
  33118. // Options
  33119. this._optionsDiv = document.createElement("div");
  33120. this._optionsDiv.id = "DebugLayerOptions";
  33121. this._optionsDiv.style.border = border;
  33122. this._optionsDiv.style.position = "absolute";
  33123. this._optionsDiv.style.background = background;
  33124. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  33125. this._optionsDiv.style.overflowY = "auto";
  33126. this._generateheader(this._optionsDiv, "OPTIONS");
  33127. this._optionsSubsetDiv = document.createElement("div");
  33128. this._optionsSubsetDiv.style.paddingTop = "5px";
  33129. this._optionsSubsetDiv.style.paddingBottom = "5px";
  33130. this._optionsSubsetDiv.style.overflowY = "auto";
  33131. this._optionsSubsetDiv.style.maxHeight = "200px";
  33132. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  33133. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  33134. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  33135. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  33136. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  33137. _this._displayTree = element.checked;
  33138. _this._needToRefreshMeshesTree = true;
  33139. });
  33140. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33141. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  33142. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  33143. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  33144. _this._labelsEnabled = element.checked;
  33145. if (!_this._labelsEnabled) {
  33146. _this._clearLabels();
  33147. }
  33148. });
  33149. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  33150. if (element.checked) {
  33151. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  33152. }
  33153. else {
  33154. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  33155. }
  33156. });
  33157. ;
  33158. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33159. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  33160. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  33161. if (element.checked) {
  33162. _this._scene.forceWireframe = false;
  33163. _this._scene.forcePointsCloud = false;
  33164. }
  33165. });
  33166. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  33167. if (element.checked) {
  33168. _this._scene.forceWireframe = true;
  33169. _this._scene.forcePointsCloud = false;
  33170. }
  33171. });
  33172. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  33173. if (element.checked) {
  33174. _this._scene.forceWireframe = false;
  33175. _this._scene.forcePointsCloud = true;
  33176. }
  33177. });
  33178. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33179. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  33180. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  33181. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  33182. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  33183. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  33184. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  33185. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  33186. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  33187. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  33188. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  33189. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  33190. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33191. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  33192. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  33193. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  33194. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  33195. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  33196. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  33197. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  33198. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  33199. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  33200. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  33201. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  33202. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  33203. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  33204. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  33205. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  33206. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  33207. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33208. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  33209. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  33210. if (element.checked) {
  33211. _this._scene.headphone = true;
  33212. }
  33213. });
  33214. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  33215. if (element.checked) {
  33216. _this._scene.headphone = false;
  33217. }
  33218. });
  33219. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  33220. _this._scene.audioEnabled = !element.checked;
  33221. });
  33222. }
  33223. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33224. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  33225. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  33226. if (!element.checked) {
  33227. _this._clearSkeletonViewers();
  33228. return;
  33229. }
  33230. for (var index = 0; index < _this._scene.meshes.length; index++) {
  33231. var mesh = _this._scene.meshes[index];
  33232. if (mesh.skeleton) {
  33233. var found = false;
  33234. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  33235. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  33236. found = true;
  33237. break;
  33238. }
  33239. }
  33240. if (found) {
  33241. continue;
  33242. }
  33243. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  33244. viewer.isEnabled = true;
  33245. _this._skeletonViewers.push(viewer);
  33246. }
  33247. }
  33248. });
  33249. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33250. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  33251. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  33252. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  33253. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  33254. if (_this._camera) {
  33255. console.log(_this._camera);
  33256. }
  33257. else {
  33258. console.warn("No camera defined, or debug layer created before camera creation!");
  33259. }
  33260. });
  33261. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33262. this._globalDiv.appendChild(this._statsDiv);
  33263. this._globalDiv.appendChild(this._logDiv);
  33264. this._globalDiv.appendChild(this._optionsDiv);
  33265. this._globalDiv.appendChild(this._treeDiv);
  33266. }
  33267. };
  33268. DebugLayer.prototype._displayStats = function () {
  33269. var scene = this._scene;
  33270. var engine = scene.getEngine();
  33271. var glInfo = engine.getGlInfo();
  33272. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  33273. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  33274. + "<b>Count</b><br>"
  33275. + "Total meshes: " + scene.meshes.length + "<br>"
  33276. + "Total lights: " + scene.lights.length + "<br>"
  33277. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  33278. + "Total materials: " + scene.materials.length + "<br>"
  33279. + "Total textures: " + scene.textures.length + "<br>"
  33280. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  33281. + "Active indices: " + scene.getActiveIndices() + "<br>"
  33282. + "Active bones: " + scene.getActiveBones() + "<br>"
  33283. + "Active particles: " + scene.getActiveParticles() + "<br>"
  33284. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  33285. + "<b>Duration</b><br>"
  33286. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  33287. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  33288. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  33289. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  33290. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  33291. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  33292. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  33293. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  33294. + "</div>"
  33295. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  33296. + "<b>Extensions</b><br>"
  33297. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  33298. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  33299. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  33300. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  33301. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  33302. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  33303. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  33304. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  33305. + "</div><br>"
  33306. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  33307. + "<b>Caps.</b><br>"
  33308. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  33309. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  33310. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  33311. + "<b>Info</b><br>"
  33312. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  33313. + glInfo.version + "<br>"
  33314. + "</div><br>"
  33315. + glInfo.renderer + "<br>";
  33316. if (this.customStatsFunction) {
  33317. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  33318. }
  33319. };
  33320. return DebugLayer;
  33321. })();
  33322. BABYLON.DebugLayer = DebugLayer;
  33323. })(BABYLON || (BABYLON = {}));
  33324. var BABYLON;
  33325. (function (BABYLON) {
  33326. var DefaultLoadingScreen = (function () {
  33327. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  33328. var _this = this;
  33329. if (_loadingText === void 0) { _loadingText = ""; }
  33330. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  33331. this._renderingCanvas = _renderingCanvas;
  33332. this._loadingText = _loadingText;
  33333. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  33334. // Resize
  33335. this._resizeLoadingUI = function () {
  33336. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  33337. _this._loadingDiv.style.position = "absolute";
  33338. _this._loadingDiv.style.left = canvasRect.left + "px";
  33339. _this._loadingDiv.style.top = canvasRect.top + "px";
  33340. _this._loadingDiv.style.width = canvasRect.width + "px";
  33341. _this._loadingDiv.style.height = canvasRect.height + "px";
  33342. };
  33343. }
  33344. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  33345. var _this = this;
  33346. if (this._loadingDiv) {
  33347. // Do not add a loading screen if there is already one
  33348. return;
  33349. }
  33350. this._loadingDiv = document.createElement("div");
  33351. this._loadingDiv.id = "babylonjsLoadingDiv";
  33352. this._loadingDiv.style.opacity = "0";
  33353. this._loadingDiv.style.transition = "opacity 1.5s ease";
  33354. // Loading text
  33355. this._loadingTextDiv = document.createElement("div");
  33356. this._loadingTextDiv.style.position = "absolute";
  33357. this._loadingTextDiv.style.left = "0";
  33358. this._loadingTextDiv.style.top = "50%";
  33359. this._loadingTextDiv.style.marginTop = "80px";
  33360. this._loadingTextDiv.style.width = "100%";
  33361. this._loadingTextDiv.style.height = "20px";
  33362. this._loadingTextDiv.style.fontFamily = "Arial";
  33363. this._loadingTextDiv.style.fontSize = "14px";
  33364. this._loadingTextDiv.style.color = "white";
  33365. this._loadingTextDiv.style.textAlign = "center";
  33366. this._loadingTextDiv.innerHTML = "Loading";
  33367. this._loadingDiv.appendChild(this._loadingTextDiv);
  33368. //set the predefined text
  33369. this._loadingTextDiv.innerHTML = this._loadingText;
  33370. // Loading img
  33371. var imgBack = new Image();
  33372. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  33373. imgBack.style.position = "absolute";
  33374. imgBack.style.left = "50%";
  33375. imgBack.style.top = "50%";
  33376. imgBack.style.marginLeft = "-50px";
  33377. imgBack.style.marginTop = "-50px";
  33378. imgBack.style.transition = "transform 1.0s ease";
  33379. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  33380. var deg = 360;
  33381. var onTransitionEnd = function () {
  33382. deg += 360;
  33383. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  33384. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  33385. };
  33386. imgBack.addEventListener("transitionend", onTransitionEnd);
  33387. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  33388. this._loadingDiv.appendChild(imgBack);
  33389. // front image
  33390. var imgFront = new Image();
  33391. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  33392. imgFront.style.position = "absolute";
  33393. imgFront.style.left = "50%";
  33394. imgFront.style.top = "50%";
  33395. imgFront.style.marginLeft = "-50px";
  33396. imgFront.style.marginTop = "-50px";
  33397. this._loadingDiv.appendChild(imgFront);
  33398. this._resizeLoadingUI();
  33399. window.addEventListener("resize", this._resizeLoadingUI);
  33400. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33401. document.body.appendChild(this._loadingDiv);
  33402. setTimeout(function () {
  33403. _this._loadingDiv.style.opacity = "1";
  33404. imgBack.style.transform = "rotateZ(360deg)";
  33405. imgBack.style.webkitTransform = "rotateZ(360deg)";
  33406. }, 0);
  33407. };
  33408. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33409. var _this = this;
  33410. if (!this._loadingDiv) {
  33411. return;
  33412. }
  33413. var onTransitionEnd = function () {
  33414. if (!_this._loadingDiv) {
  33415. return;
  33416. }
  33417. document.body.removeChild(_this._loadingDiv);
  33418. window.removeEventListener("resize", _this._resizeLoadingUI);
  33419. _this._loadingDiv = null;
  33420. };
  33421. this._loadingDiv.style.opacity = "0";
  33422. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33423. };
  33424. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33425. set: function (text) {
  33426. this._loadingText = text;
  33427. if (this._loadingTextDiv) {
  33428. this._loadingTextDiv.innerHTML = this._loadingText;
  33429. }
  33430. },
  33431. enumerable: true,
  33432. configurable: true
  33433. });
  33434. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33435. get: function () {
  33436. return this._loadingDivBackgroundColor;
  33437. },
  33438. set: function (color) {
  33439. this._loadingDivBackgroundColor = color;
  33440. if (!this._loadingDiv) {
  33441. return;
  33442. }
  33443. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33444. },
  33445. enumerable: true,
  33446. configurable: true
  33447. });
  33448. return DefaultLoadingScreen;
  33449. })();
  33450. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33451. })(BABYLON || (BABYLON = {}));
  33452. var BABYLON;
  33453. (function (BABYLON) {
  33454. var AudioEngine = (function () {
  33455. function AudioEngine() {
  33456. this._audioContext = null;
  33457. this._audioContextInitialized = false;
  33458. this.canUseWebAudio = false;
  33459. this.WarnedWebAudioUnsupported = false;
  33460. this.unlocked = false;
  33461. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33462. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33463. this.canUseWebAudio = true;
  33464. }
  33465. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  33466. this._unlockiOSaudio();
  33467. }
  33468. else {
  33469. this.unlocked = true;
  33470. }
  33471. }
  33472. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33473. get: function () {
  33474. if (!this._audioContextInitialized) {
  33475. this._initializeAudioContext();
  33476. }
  33477. return this._audioContext;
  33478. },
  33479. enumerable: true,
  33480. configurable: true
  33481. });
  33482. AudioEngine.prototype._unlockiOSaudio = function () {
  33483. var _this = this;
  33484. var unlockaudio = function () {
  33485. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  33486. var source = _this.audioContext.createBufferSource();
  33487. source.buffer = buffer;
  33488. source.connect(_this.audioContext.destination);
  33489. source.start(0);
  33490. setTimeout(function () {
  33491. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  33492. _this.unlocked = true;
  33493. window.removeEventListener('touchend', unlockaudio, false);
  33494. if (_this.onAudioUnlocked) {
  33495. _this.onAudioUnlocked();
  33496. }
  33497. }
  33498. }, 0);
  33499. };
  33500. window.addEventListener('touchend', unlockaudio, false);
  33501. };
  33502. AudioEngine.prototype._initializeAudioContext = function () {
  33503. try {
  33504. if (this.canUseWebAudio) {
  33505. this._audioContext = new AudioContext();
  33506. // create a global volume gain node
  33507. this.masterGain = this._audioContext.createGain();
  33508. this.masterGain.gain.value = 1;
  33509. this.masterGain.connect(this._audioContext.destination);
  33510. this._audioContextInitialized = true;
  33511. }
  33512. }
  33513. catch (e) {
  33514. this.canUseWebAudio = false;
  33515. BABYLON.Tools.Error("Web Audio: " + e.message);
  33516. }
  33517. };
  33518. AudioEngine.prototype.dispose = function () {
  33519. if (this.canUseWebAudio && this._audioContextInitialized) {
  33520. if (this._connectedAnalyser) {
  33521. this._connectedAnalyser.stopDebugCanvas();
  33522. this._connectedAnalyser.dispose();
  33523. this.masterGain.disconnect();
  33524. this.masterGain.connect(this._audioContext.destination);
  33525. this._connectedAnalyser = null;
  33526. }
  33527. this.masterGain.gain.value = 1;
  33528. }
  33529. this.WarnedWebAudioUnsupported = false;
  33530. };
  33531. AudioEngine.prototype.getGlobalVolume = function () {
  33532. if (this.canUseWebAudio && this._audioContextInitialized) {
  33533. return this.masterGain.gain.value;
  33534. }
  33535. else {
  33536. return -1;
  33537. }
  33538. };
  33539. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33540. if (this.canUseWebAudio && this._audioContextInitialized) {
  33541. this.masterGain.gain.value = newVolume;
  33542. }
  33543. };
  33544. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33545. if (this._connectedAnalyser) {
  33546. this._connectedAnalyser.stopDebugCanvas();
  33547. }
  33548. if (this.canUseWebAudio && this._audioContextInitialized) {
  33549. this._connectedAnalyser = analyser;
  33550. this.masterGain.disconnect();
  33551. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33552. }
  33553. };
  33554. return AudioEngine;
  33555. })();
  33556. BABYLON.AudioEngine = AudioEngine;
  33557. })(BABYLON || (BABYLON = {}));
  33558. var BABYLON;
  33559. (function (BABYLON) {
  33560. var Sound = (function () {
  33561. /**
  33562. * Create a sound and attach it to a scene
  33563. * @param name Name of your sound
  33564. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33565. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33566. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33567. */
  33568. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33569. var _this = this;
  33570. this.autoplay = false;
  33571. this.loop = false;
  33572. this.useCustomAttenuation = false;
  33573. this.spatialSound = false;
  33574. this.refDistance = 1;
  33575. this.rolloffFactor = 1;
  33576. this.maxDistance = 100;
  33577. this.distanceModel = "linear";
  33578. this._panningModel = "equalpower";
  33579. this._playbackRate = 1;
  33580. this._streaming = false;
  33581. this._startTime = 0;
  33582. this._startOffset = 0;
  33583. this._position = BABYLON.Vector3.Zero();
  33584. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33585. this._volume = 1;
  33586. this._isLoaded = false;
  33587. this._isReadyToPlay = false;
  33588. this.isPlaying = false;
  33589. this.isPaused = false;
  33590. this._isDirectional = false;
  33591. // Used if you'd like to create a directional sound.
  33592. // If not set, the sound will be omnidirectional
  33593. this._coneInnerAngle = 360;
  33594. this._coneOuterAngle = 360;
  33595. this._coneOuterGain = 0;
  33596. this._isOutputConnected = false;
  33597. this.name = name;
  33598. this._scene = scene;
  33599. this._readyToPlayCallback = readyToPlayCallback;
  33600. // Default custom attenuation function is a linear attenuation
  33601. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33602. if (currentDistance < maxDistance) {
  33603. return currentVolume * (1 - currentDistance / maxDistance);
  33604. }
  33605. else {
  33606. return 0;
  33607. }
  33608. };
  33609. if (options) {
  33610. this.autoplay = options.autoplay || false;
  33611. this.loop = options.loop || false;
  33612. // if volume === 0, we need another way to check this option
  33613. if (options.volume !== undefined) {
  33614. this._volume = options.volume;
  33615. }
  33616. this.spatialSound = options.spatialSound || false;
  33617. this.maxDistance = options.maxDistance || 100;
  33618. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33619. this.rolloffFactor = options.rolloffFactor || 1;
  33620. this.refDistance = options.refDistance || 1;
  33621. this.distanceModel = options.distanceModel || "linear";
  33622. this._playbackRate = options.playbackRate || 1;
  33623. this._streaming = options.streaming || false;
  33624. }
  33625. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33626. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33627. this._soundGain.gain.value = this._volume;
  33628. this._inputAudioNode = this._soundGain;
  33629. this._ouputAudioNode = this._soundGain;
  33630. if (this.spatialSound) {
  33631. this._createSpatialParameters();
  33632. }
  33633. this._scene.mainSoundTrack.AddSound(this);
  33634. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33635. if (urlOrArrayBuffer) {
  33636. // If it's an URL
  33637. if (typeof (urlOrArrayBuffer) === "string") {
  33638. // Loading sound using XHR2
  33639. if (!this._streaming) {
  33640. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33641. }
  33642. else {
  33643. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33644. this._htmlAudioElement.controls = false;
  33645. this._htmlAudioElement.loop = this.loop;
  33646. this._htmlAudioElement.crossOrigin = "anonymous";
  33647. this._htmlAudioElement.preload = "auto";
  33648. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33649. _this._isReadyToPlay = true;
  33650. if (_this.autoplay) {
  33651. _this.play();
  33652. }
  33653. if (_this._readyToPlayCallback) {
  33654. _this._readyToPlayCallback();
  33655. }
  33656. });
  33657. document.body.appendChild(this._htmlAudioElement);
  33658. }
  33659. }
  33660. else {
  33661. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33662. if (urlOrArrayBuffer.byteLength > 0) {
  33663. this._soundLoaded(urlOrArrayBuffer);
  33664. }
  33665. }
  33666. else {
  33667. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33668. }
  33669. }
  33670. }
  33671. }
  33672. else {
  33673. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33674. this._scene.mainSoundTrack.AddSound(this);
  33675. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33676. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33677. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33678. }
  33679. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33680. if (this._readyToPlayCallback) {
  33681. window.setTimeout(function () {
  33682. _this._readyToPlayCallback();
  33683. }, 1000);
  33684. }
  33685. }
  33686. }
  33687. Sound.prototype.dispose = function () {
  33688. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33689. if (this.isPlaying) {
  33690. this.stop();
  33691. }
  33692. this._isReadyToPlay = false;
  33693. if (this.soundTrackId === -1) {
  33694. this._scene.mainSoundTrack.RemoveSound(this);
  33695. }
  33696. else {
  33697. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33698. }
  33699. if (this._soundGain) {
  33700. this._soundGain.disconnect();
  33701. this._soundGain = null;
  33702. }
  33703. if (this._soundPanner) {
  33704. this._soundPanner.disconnect();
  33705. this._soundPanner = null;
  33706. }
  33707. if (this._soundSource) {
  33708. this._soundSource.disconnect();
  33709. this._soundSource = null;
  33710. }
  33711. this._audioBuffer = null;
  33712. if (this._htmlAudioElement) {
  33713. this._htmlAudioElement.pause();
  33714. this._htmlAudioElement.src = "";
  33715. document.body.removeChild(this._htmlAudioElement);
  33716. }
  33717. if (this._connectedMesh) {
  33718. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33719. this._connectedMesh = null;
  33720. }
  33721. }
  33722. };
  33723. Sound.prototype._soundLoaded = function (audioData) {
  33724. var _this = this;
  33725. this._isLoaded = true;
  33726. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33727. _this._audioBuffer = buffer;
  33728. _this._isReadyToPlay = true;
  33729. if (_this.autoplay) {
  33730. _this.play();
  33731. }
  33732. if (_this._readyToPlayCallback) {
  33733. _this._readyToPlayCallback();
  33734. }
  33735. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33736. };
  33737. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33738. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33739. this._audioBuffer = audioBuffer;
  33740. this._isReadyToPlay = true;
  33741. }
  33742. };
  33743. Sound.prototype.updateOptions = function (options) {
  33744. if (options) {
  33745. this.loop = options.loop || this.loop;
  33746. this.maxDistance = options.maxDistance || this.maxDistance;
  33747. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33748. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33749. this.refDistance = options.refDistance || this.refDistance;
  33750. this.distanceModel = options.distanceModel || this.distanceModel;
  33751. this._playbackRate = options.playbackRate || this._playbackRate;
  33752. this._updateSpatialParameters();
  33753. if (this.isPlaying) {
  33754. if (this._streaming) {
  33755. this._htmlAudioElement.playbackRate = this._playbackRate;
  33756. }
  33757. else {
  33758. this._soundSource.playbackRate.value = this._playbackRate;
  33759. }
  33760. }
  33761. }
  33762. };
  33763. Sound.prototype._createSpatialParameters = function () {
  33764. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33765. if (this._scene.headphone) {
  33766. this._panningModel = "HRTF";
  33767. }
  33768. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33769. this._updateSpatialParameters();
  33770. this._soundPanner.connect(this._ouputAudioNode);
  33771. this._inputAudioNode = this._soundPanner;
  33772. }
  33773. };
  33774. Sound.prototype._updateSpatialParameters = function () {
  33775. if (this.spatialSound) {
  33776. if (this.useCustomAttenuation) {
  33777. // Tricks to disable in a way embedded Web Audio attenuation
  33778. this._soundPanner.distanceModel = "linear";
  33779. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33780. this._soundPanner.refDistance = 1;
  33781. this._soundPanner.rolloffFactor = 1;
  33782. this._soundPanner.panningModel = this._panningModel;
  33783. }
  33784. else {
  33785. this._soundPanner.distanceModel = this.distanceModel;
  33786. this._soundPanner.maxDistance = this.maxDistance;
  33787. this._soundPanner.refDistance = this.refDistance;
  33788. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33789. this._soundPanner.panningModel = this._panningModel;
  33790. }
  33791. }
  33792. };
  33793. Sound.prototype.switchPanningModelToHRTF = function () {
  33794. this._panningModel = "HRTF";
  33795. this._switchPanningModel();
  33796. };
  33797. Sound.prototype.switchPanningModelToEqualPower = function () {
  33798. this._panningModel = "equalpower";
  33799. this._switchPanningModel();
  33800. };
  33801. Sound.prototype._switchPanningModel = function () {
  33802. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33803. this._soundPanner.panningModel = this._panningModel;
  33804. }
  33805. };
  33806. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33807. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33808. if (this._isOutputConnected) {
  33809. this._ouputAudioNode.disconnect();
  33810. }
  33811. this._ouputAudioNode.connect(soundTrackAudioNode);
  33812. this._isOutputConnected = true;
  33813. }
  33814. };
  33815. /**
  33816. * Transform this sound into a directional source
  33817. * @param coneInnerAngle Size of the inner cone in degree
  33818. * @param coneOuterAngle Size of the outer cone in degree
  33819. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33820. */
  33821. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33822. if (coneOuterAngle < coneInnerAngle) {
  33823. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33824. return;
  33825. }
  33826. this._coneInnerAngle = coneInnerAngle;
  33827. this._coneOuterAngle = coneOuterAngle;
  33828. this._coneOuterGain = coneOuterGain;
  33829. this._isDirectional = true;
  33830. if (this.isPlaying && this.loop) {
  33831. this.stop();
  33832. this.play();
  33833. }
  33834. };
  33835. Sound.prototype.setPosition = function (newPosition) {
  33836. this._position = newPosition;
  33837. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33838. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33839. }
  33840. };
  33841. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33842. this._localDirection = newLocalDirection;
  33843. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33844. this._updateDirection();
  33845. }
  33846. };
  33847. Sound.prototype._updateDirection = function () {
  33848. var mat = this._connectedMesh.getWorldMatrix();
  33849. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33850. direction.normalize();
  33851. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33852. };
  33853. Sound.prototype.updateDistanceFromListener = function () {
  33854. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33855. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33856. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33857. }
  33858. };
  33859. Sound.prototype.setAttenuationFunction = function (callback) {
  33860. this._customAttenuationFunction = callback;
  33861. };
  33862. /**
  33863. * Play the sound
  33864. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33865. */
  33866. Sound.prototype.play = function (time) {
  33867. var _this = this;
  33868. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33869. try {
  33870. if (this._startOffset < 0) {
  33871. time = -this._startOffset;
  33872. this._startOffset = 0;
  33873. }
  33874. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33875. if (!this._soundSource || !this._streamingSource) {
  33876. if (this.spatialSound) {
  33877. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33878. if (this._isDirectional) {
  33879. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33880. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33881. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33882. if (this._connectedMesh) {
  33883. this._updateDirection();
  33884. }
  33885. else {
  33886. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33887. }
  33888. }
  33889. }
  33890. }
  33891. if (this._streaming) {
  33892. if (!this._streamingSource) {
  33893. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33894. this._htmlAudioElement.onended = function () { _this._onended(); };
  33895. this._htmlAudioElement.playbackRate = this._playbackRate;
  33896. }
  33897. this._streamingSource.disconnect();
  33898. this._streamingSource.connect(this._inputAudioNode);
  33899. this._htmlAudioElement.play();
  33900. }
  33901. else {
  33902. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33903. this._soundSource.buffer = this._audioBuffer;
  33904. this._soundSource.connect(this._inputAudioNode);
  33905. this._soundSource.loop = this.loop;
  33906. this._soundSource.playbackRate.value = this._playbackRate;
  33907. this._soundSource.onended = function () { _this._onended(); };
  33908. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33909. }
  33910. this._startTime = startTime;
  33911. this.isPlaying = true;
  33912. this.isPaused = false;
  33913. }
  33914. catch (ex) {
  33915. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33916. }
  33917. }
  33918. };
  33919. Sound.prototype._onended = function () {
  33920. this.isPlaying = false;
  33921. if (this.onended) {
  33922. this.onended();
  33923. }
  33924. };
  33925. /**
  33926. * Stop the sound
  33927. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33928. */
  33929. Sound.prototype.stop = function (time) {
  33930. if (this.isPlaying) {
  33931. if (this._streaming) {
  33932. this._htmlAudioElement.pause();
  33933. // Test needed for Firefox or it will generate an Invalid State Error
  33934. if (this._htmlAudioElement.currentTime > 0) {
  33935. this._htmlAudioElement.currentTime = 0;
  33936. }
  33937. }
  33938. else {
  33939. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33940. this._soundSource.stop(stopTime);
  33941. if (!this.isPaused) {
  33942. this._startOffset = 0;
  33943. }
  33944. }
  33945. this.isPlaying = false;
  33946. }
  33947. };
  33948. Sound.prototype.pause = function () {
  33949. if (this.isPlaying) {
  33950. this.isPaused = true;
  33951. if (this._streaming) {
  33952. this._htmlAudioElement.pause();
  33953. }
  33954. else {
  33955. this.stop(0);
  33956. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33957. }
  33958. }
  33959. };
  33960. Sound.prototype.setVolume = function (newVolume, time) {
  33961. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33962. if (time) {
  33963. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  33964. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33965. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  33966. }
  33967. else {
  33968. this._soundGain.gain.value = newVolume;
  33969. }
  33970. }
  33971. this._volume = newVolume;
  33972. };
  33973. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33974. this._playbackRate = newPlaybackRate;
  33975. if (this.isPlaying) {
  33976. if (this._streaming) {
  33977. this._htmlAudioElement.playbackRate = this._playbackRate;
  33978. }
  33979. else {
  33980. this._soundSource.playbackRate.value = this._playbackRate;
  33981. }
  33982. }
  33983. };
  33984. Sound.prototype.getVolume = function () {
  33985. return this._volume;
  33986. };
  33987. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33988. var _this = this;
  33989. if (this._connectedMesh) {
  33990. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33991. this._registerFunc = null;
  33992. }
  33993. this._connectedMesh = meshToConnectTo;
  33994. if (!this.spatialSound) {
  33995. this.spatialSound = true;
  33996. this._createSpatialParameters();
  33997. if (this.isPlaying && this.loop) {
  33998. this.stop();
  33999. this.play();
  34000. }
  34001. }
  34002. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34003. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34004. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34005. };
  34006. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34007. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34008. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34009. this._updateDirection();
  34010. }
  34011. };
  34012. Sound.prototype.clone = function () {
  34013. var _this = this;
  34014. if (!this._streaming) {
  34015. var setBufferAndRun = function () {
  34016. if (_this._isReadyToPlay) {
  34017. clonedSound._audioBuffer = _this.getAudioBuffer();
  34018. clonedSound._isReadyToPlay = true;
  34019. if (clonedSound.autoplay) {
  34020. clonedSound.play();
  34021. }
  34022. }
  34023. else {
  34024. window.setTimeout(setBufferAndRun, 300);
  34025. }
  34026. };
  34027. var currentOptions = {
  34028. autoplay: this.autoplay, loop: this.loop,
  34029. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34030. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34031. refDistance: this.refDistance, distanceModel: this.distanceModel
  34032. };
  34033. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34034. if (this.useCustomAttenuation) {
  34035. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34036. }
  34037. clonedSound.setPosition(this._position);
  34038. clonedSound.setPlaybackRate(this._playbackRate);
  34039. setBufferAndRun();
  34040. return clonedSound;
  34041. }
  34042. else {
  34043. return null;
  34044. }
  34045. };
  34046. Sound.prototype.getAudioBuffer = function () {
  34047. return this._audioBuffer;
  34048. };
  34049. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34050. var soundName = parsedSound.name;
  34051. var soundUrl;
  34052. if (parsedSound.url) {
  34053. soundUrl = rootUrl + parsedSound.url;
  34054. }
  34055. else {
  34056. soundUrl = rootUrl + soundName;
  34057. }
  34058. var options = {
  34059. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34060. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34061. rolloffFactor: parsedSound.rolloffFactor,
  34062. refDistance: parsedSound.refDistance,
  34063. distanceModel: parsedSound.distanceModel,
  34064. playbackRate: parsedSound.playbackRate
  34065. };
  34066. var newSound;
  34067. if (!sourceSound) {
  34068. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34069. scene._addPendingData(newSound);
  34070. }
  34071. else {
  34072. var setBufferAndRun = function () {
  34073. if (sourceSound._isReadyToPlay) {
  34074. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34075. newSound._isReadyToPlay = true;
  34076. if (newSound.autoplay) {
  34077. newSound.play();
  34078. }
  34079. }
  34080. else {
  34081. window.setTimeout(setBufferAndRun, 300);
  34082. }
  34083. };
  34084. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34085. setBufferAndRun();
  34086. }
  34087. if (parsedSound.position) {
  34088. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34089. newSound.setPosition(soundPosition);
  34090. }
  34091. if (parsedSound.isDirectional) {
  34092. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34093. if (parsedSound.localDirectionToMesh) {
  34094. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34095. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34096. }
  34097. }
  34098. if (parsedSound.connectedMeshId) {
  34099. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34100. if (connectedMesh) {
  34101. newSound.attachToMesh(connectedMesh);
  34102. }
  34103. }
  34104. return newSound;
  34105. };
  34106. return Sound;
  34107. })();
  34108. BABYLON.Sound = Sound;
  34109. })(BABYLON || (BABYLON = {}));
  34110. var BABYLON;
  34111. (function (BABYLON) {
  34112. var SoundTrack = (function () {
  34113. function SoundTrack(scene, options) {
  34114. this.id = -1;
  34115. this._isMainTrack = false;
  34116. this._isInitialized = false;
  34117. this._scene = scene;
  34118. this.soundCollection = new Array();
  34119. this._options = options;
  34120. if (!this._isMainTrack) {
  34121. this._scene.soundTracks.push(this);
  34122. this.id = this._scene.soundTracks.length - 1;
  34123. }
  34124. }
  34125. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34126. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34127. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34128. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34129. if (this._options) {
  34130. if (this._options.volume) {
  34131. this._outputAudioNode.gain.value = this._options.volume;
  34132. }
  34133. if (this._options.mainTrack) {
  34134. this._isMainTrack = this._options.mainTrack;
  34135. }
  34136. }
  34137. this._isInitialized = true;
  34138. }
  34139. };
  34140. SoundTrack.prototype.dispose = function () {
  34141. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34142. if (this._connectedAnalyser) {
  34143. this._connectedAnalyser.stopDebugCanvas();
  34144. }
  34145. while (this.soundCollection.length) {
  34146. this.soundCollection[0].dispose();
  34147. }
  34148. if (this._outputAudioNode) {
  34149. this._outputAudioNode.disconnect();
  34150. }
  34151. this._outputAudioNode = null;
  34152. }
  34153. };
  34154. SoundTrack.prototype.AddSound = function (sound) {
  34155. if (!this._isInitialized) {
  34156. this._initializeSoundTrackAudioGraph();
  34157. }
  34158. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34159. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34160. }
  34161. if (sound.soundTrackId) {
  34162. if (sound.soundTrackId === -1) {
  34163. this._scene.mainSoundTrack.RemoveSound(sound);
  34164. }
  34165. else {
  34166. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34167. }
  34168. }
  34169. this.soundCollection.push(sound);
  34170. sound.soundTrackId = this.id;
  34171. };
  34172. SoundTrack.prototype.RemoveSound = function (sound) {
  34173. var index = this.soundCollection.indexOf(sound);
  34174. if (index !== -1) {
  34175. this.soundCollection.splice(index, 1);
  34176. }
  34177. };
  34178. SoundTrack.prototype.setVolume = function (newVolume) {
  34179. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34180. this._outputAudioNode.gain.value = newVolume;
  34181. }
  34182. };
  34183. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34184. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34185. for (var i = 0; i < this.soundCollection.length; i++) {
  34186. this.soundCollection[i].switchPanningModelToHRTF();
  34187. }
  34188. }
  34189. };
  34190. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34191. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34192. for (var i = 0; i < this.soundCollection.length; i++) {
  34193. this.soundCollection[i].switchPanningModelToEqualPower();
  34194. }
  34195. }
  34196. };
  34197. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34198. if (this._connectedAnalyser) {
  34199. this._connectedAnalyser.stopDebugCanvas();
  34200. }
  34201. this._connectedAnalyser = analyser;
  34202. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34203. this._outputAudioNode.disconnect();
  34204. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34205. }
  34206. };
  34207. return SoundTrack;
  34208. })();
  34209. BABYLON.SoundTrack = SoundTrack;
  34210. })(BABYLON || (BABYLON = {}));
  34211. var BABYLON;
  34212. (function (BABYLON) {
  34213. var SIMDVector3 = (function () {
  34214. function SIMDVector3() {
  34215. }
  34216. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  34217. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  34218. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34219. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34220. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34221. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34222. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  34223. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34224. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34225. };
  34226. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  34227. var v0 = SIMD.float32x4.splat(x);
  34228. var v1 = SIMD.float32x4.splat(y);
  34229. var v2 = SIMD.float32x4.splat(z);
  34230. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34231. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34232. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34233. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34234. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  34235. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34236. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34237. };
  34238. return SIMDVector3;
  34239. })();
  34240. BABYLON.SIMDVector3 = SIMDVector3;
  34241. var SIMDMatrix = (function () {
  34242. function SIMDMatrix() {
  34243. }
  34244. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  34245. if (offset === void 0) { offset = 0; }
  34246. var tm = this.m;
  34247. var om = other.m;
  34248. var om0 = SIMD.float32x4.load(om, 0);
  34249. var om1 = SIMD.float32x4.load(om, 4);
  34250. var om2 = SIMD.float32x4.load(om, 8);
  34251. var om3 = SIMD.float32x4.load(om, 12);
  34252. var tm0 = SIMD.float32x4.load(tm, 0);
  34253. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  34254. var tm1 = SIMD.float32x4.load(tm, 4);
  34255. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  34256. var tm2 = SIMD.float32x4.load(tm, 8);
  34257. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  34258. var tm3 = SIMD.float32x4.load(tm, 12);
  34259. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  34260. };
  34261. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  34262. var src = this.m;
  34263. var dest = other.m;
  34264. var row0, row1, row2, row3;
  34265. var tmp1;
  34266. var minor0, minor1, minor2, minor3;
  34267. var det;
  34268. // Load the 4 rows
  34269. var src0 = SIMD.float32x4.load(src, 0);
  34270. var src1 = SIMD.float32x4.load(src, 4);
  34271. var src2 = SIMD.float32x4.load(src, 8);
  34272. var src3 = SIMD.float32x4.load(src, 12);
  34273. // Transpose the source matrix. Sort of. Not a true transpose operation
  34274. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34275. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34276. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  34277. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  34278. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34279. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34280. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  34281. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  34282. // This is a true transposition, but it will lead to an incorrect result
  34283. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34284. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34285. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34286. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34287. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34288. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34289. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34290. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34291. // ----
  34292. tmp1 = SIMD.float32x4.mul(row2, row3);
  34293. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34294. minor0 = SIMD.float32x4.mul(row1, tmp1);
  34295. minor1 = SIMD.float32x4.mul(row0, tmp1);
  34296. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34297. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  34298. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  34299. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  34300. // ----
  34301. tmp1 = SIMD.float32x4.mul(row1, row2);
  34302. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34303. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  34304. minor3 = SIMD.float32x4.mul(row0, tmp1);
  34305. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34306. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  34307. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  34308. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  34309. // ----
  34310. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  34311. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34312. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  34313. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  34314. minor2 = SIMD.float32x4.mul(row0, tmp1);
  34315. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34316. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  34317. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  34318. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  34319. // ----
  34320. tmp1 = SIMD.float32x4.mul(row0, row1);
  34321. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34322. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  34323. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  34324. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34325. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  34326. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  34327. // ----
  34328. tmp1 = SIMD.float32x4.mul(row0, row3);
  34329. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34330. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  34331. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  34332. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34333. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  34334. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  34335. // ----
  34336. tmp1 = SIMD.float32x4.mul(row0, row2);
  34337. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34338. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  34339. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  34340. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34341. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  34342. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  34343. // Compute determinant
  34344. det = SIMD.float32x4.mul(row0, minor0);
  34345. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  34346. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  34347. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  34348. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  34349. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  34350. // These shuffles aren't necessary if the faulty transposition is done
  34351. // up at the top of this function.
  34352. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  34353. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  34354. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  34355. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  34356. // Compute final values by multiplying with 1/det
  34357. minor0 = SIMD.float32x4.mul(det, minor0);
  34358. minor1 = SIMD.float32x4.mul(det, minor1);
  34359. minor2 = SIMD.float32x4.mul(det, minor2);
  34360. minor3 = SIMD.float32x4.mul(det, minor3);
  34361. SIMD.float32x4.store(dest, 0, minor0);
  34362. SIMD.float32x4.store(dest, 4, minor1);
  34363. SIMD.float32x4.store(dest, 8, minor2);
  34364. SIMD.float32x4.store(dest, 12, minor3);
  34365. return this;
  34366. };
  34367. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  34368. var out = result.m;
  34369. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  34370. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  34371. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  34372. // cc.kmVec3Subtract(f, pCenter, pEye);
  34373. var f = SIMD.float32x4.sub(center, eye);
  34374. // cc.kmVec3Normalize(f, f);
  34375. var tmp = SIMD.float32x4.mul(f, f);
  34376. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34377. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34378. // cc.kmVec3Assign(up, pUp);
  34379. // cc.kmVec3Normalize(up, up);
  34380. tmp = SIMD.float32x4.mul(up, up);
  34381. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34382. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34383. // cc.kmVec3Cross(s, f, up);
  34384. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  34385. // cc.kmVec3Normalize(s, s);
  34386. tmp = SIMD.float32x4.mul(s, s);
  34387. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34388. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34389. // cc.kmVec3Cross(u, s, f);
  34390. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  34391. // cc.kmVec3Normalize(s, s);
  34392. tmp = SIMD.float32x4.mul(s, s);
  34393. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34394. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34395. var zero = SIMD.float32x4.splat(0.0);
  34396. s = SIMD.float32x4.neg(s);
  34397. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  34398. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  34399. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34400. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  34401. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  34402. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  34403. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34404. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  34405. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  34406. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  34407. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  34408. var b3 = SIMD.float32x4.neg(eye);
  34409. b3 = SIMD.float32x4.withW(b3, 1.0);
  34410. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  34411. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  34412. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  34413. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  34414. };
  34415. return SIMDMatrix;
  34416. })();
  34417. BABYLON.SIMDMatrix = SIMDMatrix;
  34418. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  34419. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  34420. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  34421. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  34422. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  34423. var SIMDHelper = (function () {
  34424. function SIMDHelper() {
  34425. }
  34426. Object.defineProperty(SIMDHelper, "IsEnabled", {
  34427. get: function () {
  34428. return SIMDHelper._isEnabled;
  34429. },
  34430. enumerable: true,
  34431. configurable: true
  34432. });
  34433. SIMDHelper.DisableSIMD = function () {
  34434. // Replace functions
  34435. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  34436. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  34437. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  34438. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  34439. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  34440. SIMDHelper._isEnabled = false;
  34441. };
  34442. SIMDHelper.EnableSIMD = function () {
  34443. if (window.SIMD === undefined) {
  34444. return;
  34445. }
  34446. // Replace functions
  34447. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  34448. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  34449. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  34450. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  34451. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  34452. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  34453. get: function () { return this._data[0]; },
  34454. set: function (value) {
  34455. if (!this._data) {
  34456. this._data = new Float32Array(3);
  34457. }
  34458. this._data[0] = value;
  34459. }
  34460. });
  34461. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  34462. get: function () { return this._data[1]; },
  34463. set: function (value) {
  34464. this._data[1] = value;
  34465. }
  34466. });
  34467. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  34468. get: function () { return this._data[2]; },
  34469. set: function (value) {
  34470. this._data[2] = value;
  34471. }
  34472. });
  34473. SIMDHelper._isEnabled = true;
  34474. };
  34475. SIMDHelper._isEnabled = false;
  34476. return SIMDHelper;
  34477. })();
  34478. BABYLON.SIMDHelper = SIMDHelper;
  34479. })(BABYLON || (BABYLON = {}));
  34480. var BABYLON;
  34481. (function (BABYLON) {
  34482. var ShaderMaterial = (function (_super) {
  34483. __extends(ShaderMaterial, _super);
  34484. function ShaderMaterial(name, scene, shaderPath, options) {
  34485. _super.call(this, name, scene);
  34486. this._textures = {};
  34487. this._floats = {};
  34488. this._floatsArrays = {};
  34489. this._colors3 = {};
  34490. this._colors4 = {};
  34491. this._vectors2 = {};
  34492. this._vectors3 = {};
  34493. this._vectors4 = {};
  34494. this._matrices = {};
  34495. this._matrices3x3 = {};
  34496. this._matrices2x2 = {};
  34497. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  34498. this._shaderPath = shaderPath;
  34499. options.needAlphaBlending = options.needAlphaBlending || false;
  34500. options.needAlphaTesting = options.needAlphaTesting || false;
  34501. options.attributes = options.attributes || ["position", "normal", "uv"];
  34502. options.uniforms = options.uniforms || ["worldViewProjection"];
  34503. options.samplers = options.samplers || [];
  34504. options.defines = options.defines || [];
  34505. this._options = options;
  34506. }
  34507. ShaderMaterial.prototype.needAlphaBlending = function () {
  34508. return this._options.needAlphaBlending;
  34509. };
  34510. ShaderMaterial.prototype.needAlphaTesting = function () {
  34511. return this._options.needAlphaTesting;
  34512. };
  34513. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  34514. if (this._options.uniforms.indexOf(uniformName) === -1) {
  34515. this._options.uniforms.push(uniformName);
  34516. }
  34517. };
  34518. ShaderMaterial.prototype.setTexture = function (name, texture) {
  34519. if (this._options.samplers.indexOf(name) === -1) {
  34520. this._options.samplers.push(name);
  34521. }
  34522. this._textures[name] = texture;
  34523. return this;
  34524. };
  34525. ShaderMaterial.prototype.setFloat = function (name, value) {
  34526. this._checkUniform(name);
  34527. this._floats[name] = value;
  34528. return this;
  34529. };
  34530. ShaderMaterial.prototype.setFloats = function (name, value) {
  34531. this._checkUniform(name);
  34532. this._floatsArrays[name] = value;
  34533. return this;
  34534. };
  34535. ShaderMaterial.prototype.setColor3 = function (name, value) {
  34536. this._checkUniform(name);
  34537. this._colors3[name] = value;
  34538. return this;
  34539. };
  34540. ShaderMaterial.prototype.setColor4 = function (name, value) {
  34541. this._checkUniform(name);
  34542. this._colors4[name] = value;
  34543. return this;
  34544. };
  34545. ShaderMaterial.prototype.setVector2 = function (name, value) {
  34546. this._checkUniform(name);
  34547. this._vectors2[name] = value;
  34548. return this;
  34549. };
  34550. ShaderMaterial.prototype.setVector3 = function (name, value) {
  34551. this._checkUniform(name);
  34552. this._vectors3[name] = value;
  34553. return this;
  34554. };
  34555. ShaderMaterial.prototype.setVector4 = function (name, value) {
  34556. this._checkUniform(name);
  34557. this._vectors4[name] = value;
  34558. return this;
  34559. };
  34560. ShaderMaterial.prototype.setMatrix = function (name, value) {
  34561. this._checkUniform(name);
  34562. this._matrices[name] = value;
  34563. return this;
  34564. };
  34565. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  34566. this._checkUniform(name);
  34567. this._matrices3x3[name] = value;
  34568. return this;
  34569. };
  34570. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  34571. this._checkUniform(name);
  34572. this._matrices2x2[name] = value;
  34573. return this;
  34574. };
  34575. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  34576. var scene = this.getScene();
  34577. var engine = scene.getEngine();
  34578. if (!this.checkReadyOnEveryCall) {
  34579. if (this._renderId === scene.getRenderId()) {
  34580. return true;
  34581. }
  34582. }
  34583. // Instances
  34584. var defines = [];
  34585. var fallbacks = new BABYLON.EffectFallbacks();
  34586. if (useInstances) {
  34587. defines.push("#define INSTANCES");
  34588. }
  34589. for (var index = 0; index < this._options.defines.length; index++) {
  34590. defines.push(this._options.defines[index]);
  34591. }
  34592. // Bones
  34593. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34594. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34595. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34596. fallbacks.addCPUSkinningFallback(0, mesh);
  34597. }
  34598. // Alpha test
  34599. if (engine.getAlphaTesting()) {
  34600. defines.push("#define ALPHATEST");
  34601. }
  34602. var previousEffect = this._effect;
  34603. var join = defines.join("\n");
  34604. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  34605. if (!this._effect.isReady()) {
  34606. return false;
  34607. }
  34608. if (previousEffect !== this._effect) {
  34609. scene.resetCachedMaterial();
  34610. }
  34611. this._renderId = scene.getRenderId();
  34612. return true;
  34613. };
  34614. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34615. var scene = this.getScene();
  34616. if (this._options.uniforms.indexOf("world") !== -1) {
  34617. this._effect.setMatrix("world", world);
  34618. }
  34619. if (this._options.uniforms.indexOf("worldView") !== -1) {
  34620. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  34621. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  34622. }
  34623. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  34624. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  34625. }
  34626. };
  34627. ShaderMaterial.prototype.bind = function (world, mesh) {
  34628. // Std values
  34629. this.bindOnlyWorldMatrix(world);
  34630. if (this.getScene().getCachedMaterial() !== this) {
  34631. if (this._options.uniforms.indexOf("view") !== -1) {
  34632. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  34633. }
  34634. if (this._options.uniforms.indexOf("projection") !== -1) {
  34635. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  34636. }
  34637. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  34638. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34639. }
  34640. // Bones
  34641. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34642. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  34643. }
  34644. // Texture
  34645. for (var name in this._textures) {
  34646. this._effect.setTexture(name, this._textures[name]);
  34647. }
  34648. // Float
  34649. for (name in this._floats) {
  34650. this._effect.setFloat(name, this._floats[name]);
  34651. }
  34652. // Float s
  34653. for (name in this._floatsArrays) {
  34654. this._effect.setArray(name, this._floatsArrays[name]);
  34655. }
  34656. // Color3
  34657. for (name in this._colors3) {
  34658. this._effect.setColor3(name, this._colors3[name]);
  34659. }
  34660. // Color4
  34661. for (name in this._colors4) {
  34662. var color = this._colors4[name];
  34663. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  34664. }
  34665. // Vector2
  34666. for (name in this._vectors2) {
  34667. this._effect.setVector2(name, this._vectors2[name]);
  34668. }
  34669. // Vector3
  34670. for (name in this._vectors3) {
  34671. this._effect.setVector3(name, this._vectors3[name]);
  34672. }
  34673. // Vector4
  34674. for (name in this._vectors4) {
  34675. this._effect.setVector4(name, this._vectors4[name]);
  34676. }
  34677. // Matrix
  34678. for (name in this._matrices) {
  34679. this._effect.setMatrix(name, this._matrices[name]);
  34680. }
  34681. // Matrix 3x3
  34682. for (name in this._matrices3x3) {
  34683. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  34684. }
  34685. // Matrix 2x2
  34686. for (name in this._matrices2x2) {
  34687. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  34688. }
  34689. }
  34690. _super.prototype.bind.call(this, world, mesh);
  34691. };
  34692. ShaderMaterial.prototype.clone = function (name) {
  34693. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  34694. return newShaderMaterial;
  34695. };
  34696. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34697. if (forceDisposeTextures) {
  34698. for (var name in this._textures) {
  34699. this._textures[name].dispose();
  34700. }
  34701. }
  34702. this._textures = {};
  34703. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34704. };
  34705. ShaderMaterial.prototype.serialize = function () {
  34706. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34707. serializationObject.customType = "BABYLON.ShaderMaterial";
  34708. serializationObject.options = this._options;
  34709. serializationObject.shaderPath = this._shaderPath;
  34710. // Texture
  34711. serializationObject.textures = {};
  34712. for (var name in this._textures) {
  34713. serializationObject.textures[name] = this._textures[name].serialize();
  34714. }
  34715. // Float
  34716. serializationObject.floats = {};
  34717. for (name in this._floats) {
  34718. serializationObject.floats[name] = this._floats[name];
  34719. }
  34720. // Float s
  34721. serializationObject.floatArrays = {};
  34722. for (name in this._floatsArrays) {
  34723. serializationObject.floatArrays[name] = this._floatsArrays[name];
  34724. }
  34725. // Color3
  34726. serializationObject.colors3 = {};
  34727. for (name in this._colors3) {
  34728. serializationObject.colors3[name] = this._colors3[name].asArray();
  34729. }
  34730. // Color4
  34731. serializationObject.colors4 = {};
  34732. for (name in this._colors4) {
  34733. serializationObject.colors4[name] = this._colors4[name].asArray();
  34734. }
  34735. // Vector2
  34736. serializationObject.vectors2 = {};
  34737. for (name in this._vectors2) {
  34738. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  34739. }
  34740. // Vector3
  34741. serializationObject.vectors3 = {};
  34742. for (name in this._vectors3) {
  34743. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  34744. }
  34745. // Vector4
  34746. serializationObject.vectors4 = {};
  34747. for (name in this._vectors4) {
  34748. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  34749. }
  34750. // Matrix
  34751. serializationObject.matrices = {};
  34752. for (name in this._matrices) {
  34753. serializationObject.matrices[name] = this._matrices[name].asArray();
  34754. }
  34755. // Matrix 3x3
  34756. serializationObject.matrices3x3 = {};
  34757. for (name in this._matrices3x3) {
  34758. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  34759. }
  34760. // Matrix 2x2
  34761. serializationObject.matrices2x2 = {};
  34762. for (name in this._matrices2x2) {
  34763. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  34764. }
  34765. return serializationObject;
  34766. };
  34767. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  34768. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  34769. // Texture
  34770. for (var name in source.textures) {
  34771. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  34772. }
  34773. // Float
  34774. for (name in source.floats) {
  34775. material.setFloat(name, source.floats[name]);
  34776. }
  34777. // Float s
  34778. for (name in source.floatsArrays) {
  34779. material.setFloats(name, source.floatsArrays[name]);
  34780. }
  34781. // Color3
  34782. for (name in source.colors3) {
  34783. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  34784. }
  34785. // Color4
  34786. for (name in source.colors4) {
  34787. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  34788. }
  34789. // Vector2
  34790. for (name in source.vectors2) {
  34791. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  34792. }
  34793. // Vector3
  34794. for (name in source.vectors3) {
  34795. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  34796. }
  34797. // Vector4
  34798. for (name in source.vectors4) {
  34799. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  34800. }
  34801. // Matrix
  34802. for (name in source.matrices) {
  34803. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  34804. }
  34805. // Matrix 3x3
  34806. for (name in source.matrices3x3) {
  34807. material.setMatrix3x3(name, source.matrices3x3[name]);
  34808. }
  34809. // Matrix 2x2
  34810. for (name in source.matrices2x2) {
  34811. material.setMatrix2x2(name, source.matrices2x2[name]);
  34812. }
  34813. return material;
  34814. };
  34815. return ShaderMaterial;
  34816. })(BABYLON.Material);
  34817. BABYLON.ShaderMaterial = ShaderMaterial;
  34818. })(BABYLON || (BABYLON = {}));
  34819. var BABYLON;
  34820. (function (BABYLON) {
  34821. var Internals;
  34822. (function (Internals) {
  34823. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34824. // All values and structures referenced from:
  34825. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34826. var DDS_MAGIC = 0x20534444;
  34827. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  34828. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34829. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  34830. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34831. function FourCCToInt32(value) {
  34832. return value.charCodeAt(0) +
  34833. (value.charCodeAt(1) << 8) +
  34834. (value.charCodeAt(2) << 16) +
  34835. (value.charCodeAt(3) << 24);
  34836. }
  34837. function Int32ToFourCC(value) {
  34838. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34839. }
  34840. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34841. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34842. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34843. var headerLengthInt = 31; // The header length in 32 bit ints
  34844. // Offsets into the header array
  34845. var off_magic = 0;
  34846. var off_size = 1;
  34847. var off_flags = 2;
  34848. var off_height = 3;
  34849. var off_width = 4;
  34850. var off_mipmapCount = 7;
  34851. var off_pfFlags = 20;
  34852. var off_pfFourCC = 21;
  34853. var off_RGBbpp = 22;
  34854. var off_RMask = 23;
  34855. var off_GMask = 24;
  34856. var off_BMask = 25;
  34857. var off_AMask = 26;
  34858. var off_caps1 = 27;
  34859. var off_caps2 = 28;
  34860. ;
  34861. var DDSTools = (function () {
  34862. function DDSTools() {
  34863. }
  34864. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34865. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34866. var mipmapCount = 1;
  34867. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34868. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34869. }
  34870. return {
  34871. width: header[off_width],
  34872. height: header[off_height],
  34873. mipmapCount: mipmapCount,
  34874. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34875. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34876. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34877. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  34878. };
  34879. };
  34880. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34881. var byteArray = new Uint8Array(dataLength);
  34882. var srcData = new Uint8Array(arrayBuffer);
  34883. var index = 0;
  34884. for (var y = height - 1; y >= 0; y--) {
  34885. for (var x = 0; x < width; x++) {
  34886. var srcPos = dataOffset + (x + y * width) * 4;
  34887. byteArray[index + 2] = srcData[srcPos];
  34888. byteArray[index + 1] = srcData[srcPos + 1];
  34889. byteArray[index] = srcData[srcPos + 2];
  34890. byteArray[index + 3] = srcData[srcPos + 3];
  34891. index += 4;
  34892. }
  34893. }
  34894. return byteArray;
  34895. };
  34896. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34897. var byteArray = new Uint8Array(dataLength);
  34898. var srcData = new Uint8Array(arrayBuffer);
  34899. var index = 0;
  34900. for (var y = height - 1; y >= 0; y--) {
  34901. for (var x = 0; x < width; x++) {
  34902. var srcPos = dataOffset + (x + y * width) * 3;
  34903. byteArray[index + 2] = srcData[srcPos];
  34904. byteArray[index + 1] = srcData[srcPos + 1];
  34905. byteArray[index] = srcData[srcPos + 2];
  34906. index += 3;
  34907. }
  34908. }
  34909. return byteArray;
  34910. };
  34911. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34912. var byteArray = new Uint8Array(dataLength);
  34913. var srcData = new Uint8Array(arrayBuffer);
  34914. var index = 0;
  34915. for (var y = height - 1; y >= 0; y--) {
  34916. for (var x = 0; x < width; x++) {
  34917. var srcPos = dataOffset + (x + y * width);
  34918. byteArray[index] = srcData[srcPos];
  34919. index++;
  34920. }
  34921. }
  34922. return byteArray;
  34923. };
  34924. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  34925. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  34926. if (header[off_magic] != DDS_MAGIC) {
  34927. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34928. return;
  34929. }
  34930. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34931. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34932. return;
  34933. }
  34934. if (info.isFourCC) {
  34935. fourCC = header[off_pfFourCC];
  34936. switch (fourCC) {
  34937. case FOURCC_DXT1:
  34938. blockBytes = 8;
  34939. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34940. break;
  34941. case FOURCC_DXT3:
  34942. blockBytes = 16;
  34943. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34944. break;
  34945. case FOURCC_DXT5:
  34946. blockBytes = 16;
  34947. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34948. break;
  34949. default:
  34950. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34951. return;
  34952. }
  34953. }
  34954. mipmapCount = 1;
  34955. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34956. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34957. }
  34958. var bpp = header[off_RGBbpp];
  34959. for (var face = 0; face < faces; face++) {
  34960. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34961. width = header[off_width];
  34962. height = header[off_height];
  34963. dataOffset = header[off_size] + 4;
  34964. for (i = 0; i < mipmapCount; ++i) {
  34965. if (info.isRGB) {
  34966. if (bpp === 24) {
  34967. dataLength = width * height * 3;
  34968. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34969. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34970. }
  34971. else {
  34972. dataLength = width * height * 4;
  34973. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34974. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34975. }
  34976. }
  34977. else if (info.isLuminance) {
  34978. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34979. var unpaddedRowSize = width;
  34980. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34981. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34982. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34983. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34984. }
  34985. else {
  34986. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34987. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34988. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  34989. }
  34990. dataOffset += dataLength;
  34991. width *= 0.5;
  34992. height *= 0.5;
  34993. width = Math.max(1.0, width);
  34994. height = Math.max(1.0, height);
  34995. }
  34996. }
  34997. };
  34998. return DDSTools;
  34999. })();
  35000. Internals.DDSTools = DDSTools;
  35001. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35002. })(BABYLON || (BABYLON = {}));
  35003. var BABYLON;
  35004. (function (BABYLON) {
  35005. var CannonJSPlugin = (function () {
  35006. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  35007. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  35008. if (iterations === void 0) { iterations = 10; }
  35009. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  35010. this.name = "CannonJSPlugin";
  35011. this._physicsMaterials = [];
  35012. this._fixedTimeStep = 1 / 60;
  35013. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  35014. this._currentCollisionGroup = 2;
  35015. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  35016. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  35017. this._tmpPosition = BABYLON.Vector3.Zero();
  35018. this._tmpQuaternion = new BABYLON.Quaternion();
  35019. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  35020. this._tmpDeltaRotation = new BABYLON.Quaternion();
  35021. this._tmpUnityRotation = new BABYLON.Quaternion();
  35022. if (!this.isSupported()) {
  35023. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  35024. return;
  35025. }
  35026. this.world = new CANNON.World();
  35027. this.world.broadphase = new CANNON.NaiveBroadphase();
  35028. this.world.solver.iterations = iterations;
  35029. }
  35030. CannonJSPlugin.prototype.setGravity = function (gravity) {
  35031. this.world.gravity.copy(gravity);
  35032. };
  35033. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  35034. this._fixedTimeStep = timeStep;
  35035. };
  35036. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  35037. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  35038. };
  35039. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  35040. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  35041. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  35042. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  35043. };
  35044. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  35045. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  35046. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  35047. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  35048. };
  35049. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  35050. //parent-child relationship. Does this impostor has a parent impostor?
  35051. if (impostor.parent) {
  35052. if (impostor.physicsBody) {
  35053. this.removePhysicsBody(impostor);
  35054. //TODO is that needed?
  35055. impostor.forceUpdate();
  35056. }
  35057. return;
  35058. }
  35059. //should a new body be created for this impostor?
  35060. if (impostor.isBodyInitRequired()) {
  35061. var shape = this._createShape(impostor);
  35062. //unregister events, if body is being changed
  35063. var oldBody = impostor.physicsBody;
  35064. if (oldBody) {
  35065. this.removePhysicsBody(impostor);
  35066. }
  35067. //create the body and material
  35068. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  35069. var bodyCreationObject = {
  35070. mass: impostor.getParam("mass"),
  35071. material: material
  35072. };
  35073. // A simple extend, in case native options were used.
  35074. var nativeOptions = impostor.getParam("nativeOptions");
  35075. for (var key in nativeOptions) {
  35076. if (nativeOptions.hasOwnProperty(key)) {
  35077. bodyCreationObject[key] = nativeOptions[key];
  35078. }
  35079. }
  35080. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  35081. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  35082. this.world.addEventListener("preStep", impostor.beforeStep);
  35083. this.world.addEventListener("postStep", impostor.afterStep);
  35084. impostor.physicsBody.addShape(shape);
  35085. this.world.add(impostor.physicsBody);
  35086. //try to keep the body moving in the right direction by taking old properties.
  35087. //Should be tested!
  35088. if (oldBody) {
  35089. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  35090. impostor.physicsBody[param].copy(oldBody[param]);
  35091. });
  35092. }
  35093. this._processChildMeshes(impostor);
  35094. }
  35095. //now update the body's transformation
  35096. this._updatePhysicsBodyTransformation(impostor);
  35097. };
  35098. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  35099. var _this = this;
  35100. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  35101. if (meshChildren.length) {
  35102. var processMesh = function (localPosition, mesh) {
  35103. var childImpostor = mesh.getPhysicsImpostor();
  35104. if (childImpostor) {
  35105. var parent = childImpostor.parent;
  35106. if (parent !== mainImpostor) {
  35107. var localPosition = mesh.position;
  35108. if (childImpostor.physicsBody) {
  35109. _this.removePhysicsBody(childImpostor);
  35110. childImpostor.physicsBody = null;
  35111. }
  35112. childImpostor.parent = mainImpostor;
  35113. childImpostor.resetUpdateFlags();
  35114. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  35115. //Add the mass of the children.
  35116. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  35117. }
  35118. }
  35119. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  35120. };
  35121. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  35122. }
  35123. };
  35124. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  35125. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  35126. this.world.removeEventListener("preStep", impostor.beforeStep);
  35127. this.world.removeEventListener("postStep", impostor.afterStep);
  35128. this.world.remove(impostor.physicsBody);
  35129. };
  35130. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  35131. var mainBody = impostorJoint.mainImpostor.physicsBody;
  35132. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  35133. if (!mainBody || !connectedBody) {
  35134. return;
  35135. }
  35136. var constraint;
  35137. var jointData = impostorJoint.joint.jointData;
  35138. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  35139. var constraintData = {
  35140. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  35141. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  35142. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  35143. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  35144. maxForce: jointData.nativeParams.maxForce,
  35145. collideConnected: !!jointData.collision
  35146. };
  35147. //Not needed, Cannon has a collideConnected flag
  35148. /*if (!jointData.collision) {
  35149. //add 1st body to a collision group of its own, if it is not in 1
  35150. if (mainBody.collisionFilterGroup === 1) {
  35151. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  35152. this._currentCollisionGroup <<= 1;
  35153. }
  35154. if (connectedBody.collisionFilterGroup === 1) {
  35155. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  35156. this._currentCollisionGroup <<= 1;
  35157. }
  35158. //add their mask to the collisionFilterMask of each other:
  35159. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  35160. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  35161. }*/
  35162. switch (impostorJoint.joint.type) {
  35163. case BABYLON.PhysicsJoint.HingeJoint:
  35164. case BABYLON.PhysicsJoint.Hinge2Joint:
  35165. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  35166. break;
  35167. case BABYLON.PhysicsJoint.DistanceJoint:
  35168. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  35169. break;
  35170. case BABYLON.PhysicsJoint.SpringJoint:
  35171. var springData = jointData;
  35172. constraint = new CANNON.Spring(mainBody, connectedBody, {
  35173. restLength: springData.length,
  35174. stiffness: springData.stiffness,
  35175. damping: springData.damping,
  35176. localAnchorA: constraintData.pivotA,
  35177. localAnchorB: constraintData.pivotB
  35178. });
  35179. break;
  35180. case BABYLON.PhysicsJoint.PointToPointJoint:
  35181. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  35182. default:
  35183. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  35184. break;
  35185. }
  35186. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  35187. constraint.collideConnected = !!jointData.collision;
  35188. impostorJoint.joint.physicsJoint = constraint;
  35189. //don't add spring as constraint, as it is not one.
  35190. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  35191. this.world.addConstraint(constraint);
  35192. }
  35193. else {
  35194. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  35195. constraint.applyForce();
  35196. });
  35197. }
  35198. };
  35199. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  35200. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  35201. };
  35202. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  35203. var index;
  35204. var mat;
  35205. for (index = 0; index < this._physicsMaterials.length; index++) {
  35206. mat = this._physicsMaterials[index];
  35207. if (mat.friction === friction && mat.restitution === restitution) {
  35208. return mat;
  35209. }
  35210. }
  35211. var currentMat = new CANNON.Material(name);
  35212. currentMat.friction = friction;
  35213. currentMat.restitution = restitution;
  35214. this._physicsMaterials.push(currentMat);
  35215. return currentMat;
  35216. };
  35217. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  35218. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  35219. };
  35220. CannonJSPlugin.prototype._createShape = function (impostor) {
  35221. var object = impostor.object;
  35222. var returnValue;
  35223. var extendSize = impostor.getObjectExtendSize();
  35224. switch (impostor.type) {
  35225. case BABYLON.PhysicsEngine.SphereImpostor:
  35226. var radiusX = extendSize.x;
  35227. var radiusY = extendSize.y;
  35228. var radiusZ = extendSize.z;
  35229. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  35230. break;
  35231. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  35232. case BABYLON.PhysicsImpostor.CylinderImpostor:
  35233. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  35234. break;
  35235. case BABYLON.PhysicsImpostor.BoxImpostor:
  35236. var box = extendSize.scale(0.5);
  35237. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  35238. break;
  35239. case BABYLON.PhysicsImpostor.PlaneImpostor:
  35240. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  35241. returnValue = new CANNON.Plane();
  35242. break;
  35243. case BABYLON.PhysicsImpostor.MeshImpostor:
  35244. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  35245. var rawFaces = object.getIndices ? object.getIndices() : [];
  35246. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  35247. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  35248. break;
  35249. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  35250. returnValue = this._createHeightmap(object);
  35251. break;
  35252. case BABYLON.PhysicsImpostor.ParticleImpostor:
  35253. returnValue = new CANNON.Particle();
  35254. break;
  35255. }
  35256. return returnValue;
  35257. };
  35258. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  35259. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35260. var matrix = [];
  35261. //For now pointDepth will not be used and will be automatically calculated.
  35262. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  35263. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  35264. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  35265. var elementSize = dim * 2 / arraySize;
  35266. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  35267. for (var i = 0; i < pos.length; i = i + 3) {
  35268. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  35269. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  35270. var y = pos[i + 1] + minY;
  35271. if (!matrix[x]) {
  35272. matrix[x] = [];
  35273. }
  35274. if (!matrix[x][z]) {
  35275. matrix[x][z] = y;
  35276. }
  35277. matrix[x][z] = Math.max(y, matrix[x][z]);
  35278. }
  35279. for (var x = 0; x <= arraySize; ++x) {
  35280. if (!matrix[x]) {
  35281. var loc = 1;
  35282. while (!matrix[(x + loc) % arraySize]) {
  35283. loc++;
  35284. }
  35285. matrix[x] = matrix[(x + loc) % arraySize].slice();
  35286. }
  35287. for (var z = 0; z <= arraySize; ++z) {
  35288. if (!matrix[x][z]) {
  35289. var loc = 1;
  35290. var newValue;
  35291. while (newValue === undefined) {
  35292. newValue = matrix[x][(z + loc++) % arraySize];
  35293. }
  35294. matrix[x][z] = newValue;
  35295. }
  35296. }
  35297. }
  35298. var shape = new CANNON.Heightfield(matrix, {
  35299. elementSize: elementSize
  35300. });
  35301. //For future reference, needed for body transformation
  35302. shape.minY = minY;
  35303. return shape;
  35304. };
  35305. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  35306. var object = impostor.object;
  35307. //make sure it is updated...
  35308. object.computeWorldMatrix && object.computeWorldMatrix(true);
  35309. // The delta between the mesh position and the mesh bounding box center
  35310. var center = impostor.getObjectCenter();
  35311. var extendSize = impostor.getObjectExtendSize();
  35312. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  35313. this._tmpPosition.copyFrom(center);
  35314. var quaternion = object.rotationQuaternion;
  35315. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  35316. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  35317. //-90 DEG in X, precalculated
  35318. quaternion = quaternion.multiply(this._minus90X);
  35319. //Invert! (Precalculated, 90 deg in X)
  35320. //No need to clone. this will never change.
  35321. impostor.setDeltaRotation(this._plus90X);
  35322. }
  35323. //If it is a heightfield, if should be centered.
  35324. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  35325. var mesh = object;
  35326. //calculate the correct body position:
  35327. var rotationQuaternion = mesh.rotationQuaternion;
  35328. mesh.rotationQuaternion = this._tmpUnityRotation;
  35329. mesh.computeWorldMatrix(true);
  35330. //get original center with no rotation
  35331. var c = center.clone();
  35332. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  35333. //rotation is back
  35334. mesh.rotationQuaternion = rotationQuaternion;
  35335. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  35336. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  35337. mesh.setPivotMatrix(p);
  35338. mesh.computeWorldMatrix(true);
  35339. //calculate the translation
  35340. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  35341. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  35342. //add it inverted to the delta
  35343. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  35344. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  35345. mesh.setPivotMatrix(oldPivot);
  35346. mesh.computeWorldMatrix(true);
  35347. }
  35348. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  35349. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  35350. this._tmpPosition.copyFrom(object.position);
  35351. }
  35352. impostor.setDeltaPosition(this._tmpDeltaPosition);
  35353. //Now update the impostor object
  35354. impostor.physicsBody.position.copy(this._tmpPosition);
  35355. impostor.physicsBody.quaternion.copy(quaternion);
  35356. };
  35357. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  35358. impostor.object.position.copyFrom(impostor.physicsBody.position);
  35359. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  35360. };
  35361. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  35362. impostor.physicsBody.position.copy(newPosition);
  35363. impostor.physicsBody.quaternion.copy(newRotation);
  35364. };
  35365. CannonJSPlugin.prototype.isSupported = function () {
  35366. return window.CANNON !== undefined;
  35367. };
  35368. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  35369. impostor.physicsBody.velocity.copy(velocity);
  35370. };
  35371. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  35372. impostor.physicsBody.angularVelocity.copy(velocity);
  35373. };
  35374. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  35375. var v = impostor.physicsBody.velocity;
  35376. if (!v)
  35377. return null;
  35378. return new BABYLON.Vector3(v.x, v.y, v.z);
  35379. };
  35380. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  35381. var v = impostor.physicsBody.angularVelocity;
  35382. if (!v)
  35383. return null;
  35384. return new BABYLON.Vector3(v.x, v.y, v.z);
  35385. };
  35386. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  35387. impostor.physicsBody.mass = mass;
  35388. impostor.physicsBody.updateMassProperties();
  35389. };
  35390. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  35391. impostor.physicsBody.sleep();
  35392. };
  35393. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  35394. impostor.physicsBody.wakeUp();
  35395. };
  35396. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  35397. joint.physicsJoint.distance = maxDistance;
  35398. };
  35399. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  35400. if (!motorIndex) {
  35401. joint.physicsJoint.enableMotor();
  35402. }
  35403. };
  35404. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  35405. if (!motorIndex) {
  35406. joint.physicsJoint.disableMotor();
  35407. }
  35408. };
  35409. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35410. if (!motorIndex) {
  35411. joint.physicsJoint.enableMotor();
  35412. joint.physicsJoint.setMotorSpeed(speed);
  35413. if (maxForce) {
  35414. this.setLimit(joint, maxForce);
  35415. }
  35416. }
  35417. };
  35418. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  35419. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  35420. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  35421. };
  35422. CannonJSPlugin.prototype.dispose = function () {
  35423. //nothing to do, actually.
  35424. };
  35425. return CannonJSPlugin;
  35426. })();
  35427. BABYLON.CannonJSPlugin = CannonJSPlugin;
  35428. })(BABYLON || (BABYLON = {}));
  35429. var BABYLON;
  35430. (function (BABYLON) {
  35431. var OimoJSPlugin = (function () {
  35432. function OimoJSPlugin(iterations) {
  35433. this.name = "OimoJSPlugin";
  35434. this._tmpImpostorsArray = [];
  35435. this._tmpPositionVector = BABYLON.Vector3.Zero();
  35436. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  35437. this.world.clear();
  35438. //making sure no stats are calculated
  35439. this.world.isNoStat = true;
  35440. }
  35441. OimoJSPlugin.prototype.setGravity = function (gravity) {
  35442. this.world.gravity.copy(gravity);
  35443. };
  35444. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  35445. this.world.timeStep = timeStep;
  35446. };
  35447. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  35448. var _this = this;
  35449. impostors.forEach(function (impostor) {
  35450. impostor.beforeStep();
  35451. });
  35452. this.world.step();
  35453. impostors.forEach(function (impostor) {
  35454. impostor.afterStep();
  35455. //update the ordered impostors array
  35456. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  35457. });
  35458. //check for collisions
  35459. var contact = this.world.contacts;
  35460. while (contact !== null) {
  35461. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  35462. contact = contact.next;
  35463. continue;
  35464. }
  35465. //is this body colliding with any other? get the impostor
  35466. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  35467. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  35468. if (!mainImpostor || !collidingImpostor) {
  35469. contact = contact.next;
  35470. continue;
  35471. }
  35472. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  35473. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  35474. contact = contact.next;
  35475. }
  35476. };
  35477. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  35478. var mass = impostor.physicsBody.massInfo.mass;
  35479. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  35480. };
  35481. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  35482. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  35483. this.applyImpulse(impostor, force, contactPoint);
  35484. };
  35485. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  35486. var _this = this;
  35487. //parent-child relationship. Does this impostor has a parent impostor?
  35488. if (impostor.parent) {
  35489. if (impostor.physicsBody) {
  35490. this.removePhysicsBody(impostor);
  35491. //TODO is that needed?
  35492. impostor.forceUpdate();
  35493. }
  35494. return;
  35495. }
  35496. if (impostor.isBodyInitRequired()) {
  35497. var bodyConfig = {
  35498. name: impostor.uniqueId,
  35499. //Oimo must have mass, also for static objects.
  35500. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  35501. size: [],
  35502. type: [],
  35503. pos: [],
  35504. rot: [],
  35505. move: impostor.getParam("mass") !== 0,
  35506. //Supporting older versions of Oimo
  35507. world: this.world
  35508. };
  35509. var impostors = [impostor];
  35510. function addToArray(parent) {
  35511. if (!parent.getChildMeshes)
  35512. return;
  35513. parent.getChildMeshes().forEach(function (m) {
  35514. if (m.physicsImpostor) {
  35515. impostors.push(m.physicsImpostor);
  35516. m.physicsImpostor._init();
  35517. }
  35518. });
  35519. }
  35520. addToArray(impostor.object);
  35521. function checkWithEpsilon(value) {
  35522. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  35523. }
  35524. impostors.forEach(function (i) {
  35525. //get the correct bounding box
  35526. var oldQuaternion = i.object.rotationQuaternion;
  35527. var rot = new OIMO.Euler().setFromQuaternion({
  35528. x: impostor.object.rotationQuaternion.x,
  35529. y: impostor.object.rotationQuaternion.y,
  35530. z: impostor.object.rotationQuaternion.z,
  35531. s: impostor.object.rotationQuaternion.w
  35532. });
  35533. var extendSize = i.getObjectExtendSize();
  35534. if (i === impostor) {
  35535. var center = impostor.getObjectCenter();
  35536. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  35537. //Can also use Array.prototype.push.apply
  35538. bodyConfig.pos.push(center.x);
  35539. bodyConfig.pos.push(center.y);
  35540. bodyConfig.pos.push(center.z);
  35541. //tmp solution
  35542. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  35543. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  35544. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  35545. }
  35546. else {
  35547. bodyConfig.pos.push(i.object.position.x);
  35548. bodyConfig.pos.push(i.object.position.y);
  35549. bodyConfig.pos.push(i.object.position.z);
  35550. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  35551. bodyConfig.rot.push(0);
  35552. bodyConfig.rot.push(0);
  35553. bodyConfig.rot.push(0);
  35554. }
  35555. // register mesh
  35556. switch (i.type) {
  35557. case BABYLON.PhysicsImpostor.ParticleImpostor:
  35558. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  35559. case BABYLON.PhysicsImpostor.SphereImpostor:
  35560. var radiusX = extendSize.x;
  35561. var radiusY = extendSize.y;
  35562. var radiusZ = extendSize.z;
  35563. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  35564. bodyConfig.type.push('sphere');
  35565. //due to the way oimo works with compounds, add 3 times
  35566. bodyConfig.size.push(size);
  35567. bodyConfig.size.push(size);
  35568. bodyConfig.size.push(size);
  35569. break;
  35570. case BABYLON.PhysicsImpostor.CylinderImpostor:
  35571. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  35572. var sizeY = checkWithEpsilon(extendSize.y);
  35573. bodyConfig.type.push('cylinder');
  35574. bodyConfig.size.push(sizeX);
  35575. bodyConfig.size.push(sizeY);
  35576. //due to the way oimo works with compounds, add one more value.
  35577. bodyConfig.size.push(sizeY);
  35578. break;
  35579. case BABYLON.PhysicsImpostor.PlaneImpostor:
  35580. case BABYLON.PhysicsImpostor.BoxImpostor:
  35581. default:
  35582. var sizeX = checkWithEpsilon(extendSize.x);
  35583. var sizeY = checkWithEpsilon(extendSize.y);
  35584. var sizeZ = checkWithEpsilon(extendSize.z);
  35585. bodyConfig.type.push('box');
  35586. bodyConfig.size.push(sizeX);
  35587. bodyConfig.size.push(sizeY);
  35588. bodyConfig.size.push(sizeZ);
  35589. break;
  35590. }
  35591. //actually not needed, but hey...
  35592. i.object.rotationQuaternion = oldQuaternion;
  35593. });
  35594. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  35595. }
  35596. else {
  35597. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  35598. }
  35599. impostor.setDeltaPosition(this._tmpPositionVector);
  35600. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  35601. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  35602. };
  35603. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  35604. //impostor.physicsBody.dispose();
  35605. //Same as : (older oimo versions)
  35606. this.world.removeRigidBody(impostor.physicsBody);
  35607. };
  35608. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  35609. var mainBody = impostorJoint.mainImpostor.physicsBody;
  35610. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  35611. if (!mainBody || !connectedBody) {
  35612. return;
  35613. }
  35614. var jointData = impostorJoint.joint.jointData;
  35615. var options = jointData.nativeParams || {};
  35616. var type;
  35617. var nativeJointData = {
  35618. body1: mainBody,
  35619. body2: connectedBody,
  35620. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  35621. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  35622. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  35623. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  35624. min: options.min,
  35625. max: options.max,
  35626. collision: options.collision || jointData.collision,
  35627. spring: options.spring,
  35628. //supporting older version of Oimo
  35629. world: this.world
  35630. };
  35631. switch (impostorJoint.joint.type) {
  35632. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  35633. type = "jointBall";
  35634. break;
  35635. case BABYLON.PhysicsJoint.SpringJoint:
  35636. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  35637. var springData = jointData;
  35638. nativeJointData.min = springData.length || nativeJointData.min;
  35639. //Max should also be set, just make sure it is at least min
  35640. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  35641. case BABYLON.PhysicsJoint.DistanceJoint:
  35642. type = "jointDistance";
  35643. nativeJointData.max = jointData.maxDistance;
  35644. break;
  35645. case BABYLON.PhysicsJoint.PrismaticJoint:
  35646. type = "jointPrisme";
  35647. break;
  35648. case BABYLON.PhysicsJoint.SliderJoint:
  35649. type = "jointSlide";
  35650. break;
  35651. case BABYLON.PhysicsJoint.WheelJoint:
  35652. type = "jointWheel";
  35653. break;
  35654. case BABYLON.PhysicsJoint.HingeJoint:
  35655. default:
  35656. type = "jointHinge";
  35657. break;
  35658. }
  35659. nativeJointData.type = type;
  35660. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  35661. };
  35662. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  35663. //Bug in Oimo prevents us from disposing a joint in the playground
  35664. //joint.joint.physicsJoint.dispose();
  35665. //So we will bruteforce it!
  35666. try {
  35667. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  35668. }
  35669. catch (e) {
  35670. BABYLON.Tools.Warn(e);
  35671. }
  35672. };
  35673. OimoJSPlugin.prototype.isSupported = function () {
  35674. return OIMO !== undefined;
  35675. };
  35676. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  35677. if (!impostor.physicsBody.sleeping) {
  35678. //TODO check that
  35679. if (impostor.physicsBody.shapes.next) {
  35680. var parentShape = this._getLastShape(impostor.physicsBody);
  35681. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  35682. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  35683. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  35684. }
  35685. else {
  35686. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  35687. }
  35688. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  35689. }
  35690. };
  35691. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  35692. var body = impostor.physicsBody;
  35693. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  35694. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  35695. body.syncShapes();
  35696. body.awake();
  35697. };
  35698. OimoJSPlugin.prototype._getLastShape = function (body) {
  35699. var lastShape = body.shapes;
  35700. while (lastShape.next) {
  35701. lastShape = lastShape.next;
  35702. }
  35703. return lastShape;
  35704. };
  35705. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  35706. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  35707. };
  35708. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  35709. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  35710. };
  35711. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  35712. var v = impostor.physicsBody.linearVelocity;
  35713. if (!v)
  35714. return null;
  35715. return new BABYLON.Vector3(v.x, v.y, v.z);
  35716. };
  35717. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  35718. var v = impostor.physicsBody.angularVelocity;
  35719. if (!v)
  35720. return null;
  35721. return new BABYLON.Vector3(v.x, v.y, v.z);
  35722. };
  35723. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  35724. var staticBody = mass === 0;
  35725. //this will actually set the body's density and not its mass.
  35726. //But this is how oimo treats the mass variable.
  35727. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  35728. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  35729. };
  35730. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  35731. impostor.physicsBody.sleep();
  35732. };
  35733. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  35734. impostor.physicsBody.awake();
  35735. };
  35736. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  35737. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  35738. if (minDistance !== void 0) {
  35739. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  35740. }
  35741. };
  35742. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35743. //TODO separate rotational and transational motors.
  35744. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  35745. if (motor) {
  35746. motor.setMotor(speed, maxForce);
  35747. }
  35748. };
  35749. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  35750. //TODO separate rotational and transational motors.
  35751. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  35752. if (motor) {
  35753. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  35754. }
  35755. };
  35756. OimoJSPlugin.prototype.dispose = function () {
  35757. this.world.clear();
  35758. };
  35759. return OimoJSPlugin;
  35760. })();
  35761. BABYLON.OimoJSPlugin = OimoJSPlugin;
  35762. })(BABYLON || (BABYLON = {}));
  35763. var BABYLON;
  35764. (function (BABYLON) {
  35765. var DisplayPassPostProcess = (function (_super) {
  35766. __extends(DisplayPassPostProcess, _super);
  35767. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35768. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  35769. }
  35770. return DisplayPassPostProcess;
  35771. })(BABYLON.PostProcess);
  35772. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  35773. })(BABYLON || (BABYLON = {}));
  35774. var BABYLON;
  35775. (function (BABYLON) {
  35776. var SimplificationSettings = (function () {
  35777. function SimplificationSettings(quality, distance, optimizeMesh) {
  35778. this.quality = quality;
  35779. this.distance = distance;
  35780. this.optimizeMesh = optimizeMesh;
  35781. }
  35782. return SimplificationSettings;
  35783. })();
  35784. BABYLON.SimplificationSettings = SimplificationSettings;
  35785. var SimplificationQueue = (function () {
  35786. function SimplificationQueue() {
  35787. this.running = false;
  35788. this._simplificationArray = [];
  35789. }
  35790. SimplificationQueue.prototype.addTask = function (task) {
  35791. this._simplificationArray.push(task);
  35792. };
  35793. SimplificationQueue.prototype.executeNext = function () {
  35794. var task = this._simplificationArray.pop();
  35795. if (task) {
  35796. this.running = true;
  35797. this.runSimplification(task);
  35798. }
  35799. else {
  35800. this.running = false;
  35801. }
  35802. };
  35803. SimplificationQueue.prototype.runSimplification = function (task) {
  35804. var _this = this;
  35805. if (task.parallelProcessing) {
  35806. //parallel simplifier
  35807. task.settings.forEach(function (setting) {
  35808. var simplifier = _this.getSimplifier(task);
  35809. simplifier.simplify(setting, function (newMesh) {
  35810. task.mesh.addLODLevel(setting.distance, newMesh);
  35811. newMesh.isVisible = true;
  35812. //check if it is the last
  35813. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  35814. //all done, run the success callback.
  35815. task.successCallback();
  35816. }
  35817. _this.executeNext();
  35818. });
  35819. });
  35820. }
  35821. else {
  35822. //single simplifier.
  35823. var simplifier = this.getSimplifier(task);
  35824. var runDecimation = function (setting, callback) {
  35825. simplifier.simplify(setting, function (newMesh) {
  35826. task.mesh.addLODLevel(setting.distance, newMesh);
  35827. newMesh.isVisible = true;
  35828. //run the next quality level
  35829. callback();
  35830. });
  35831. };
  35832. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  35833. runDecimation(task.settings[loop.index], function () {
  35834. loop.executeNext();
  35835. });
  35836. }, function () {
  35837. //execution ended, run the success callback.
  35838. if (task.successCallback) {
  35839. task.successCallback();
  35840. }
  35841. _this.executeNext();
  35842. });
  35843. }
  35844. };
  35845. SimplificationQueue.prototype.getSimplifier = function (task) {
  35846. switch (task.simplificationType) {
  35847. case SimplificationType.QUADRATIC:
  35848. default:
  35849. return new QuadraticErrorSimplification(task.mesh);
  35850. }
  35851. };
  35852. return SimplificationQueue;
  35853. })();
  35854. BABYLON.SimplificationQueue = SimplificationQueue;
  35855. /**
  35856. * The implemented types of simplification.
  35857. * At the moment only Quadratic Error Decimation is implemented.
  35858. */
  35859. (function (SimplificationType) {
  35860. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  35861. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  35862. var SimplificationType = BABYLON.SimplificationType;
  35863. var DecimationTriangle = (function () {
  35864. function DecimationTriangle(vertices) {
  35865. this.vertices = vertices;
  35866. this.error = new Array(4);
  35867. this.deleted = false;
  35868. this.isDirty = false;
  35869. this.deletePending = false;
  35870. this.borderFactor = 0;
  35871. }
  35872. return DecimationTriangle;
  35873. })();
  35874. BABYLON.DecimationTriangle = DecimationTriangle;
  35875. var DecimationVertex = (function () {
  35876. function DecimationVertex(position, id) {
  35877. this.position = position;
  35878. this.id = id;
  35879. this.isBorder = true;
  35880. this.q = new QuadraticMatrix();
  35881. this.triangleCount = 0;
  35882. this.triangleStart = 0;
  35883. this.originalOffsets = [];
  35884. }
  35885. DecimationVertex.prototype.updatePosition = function (newPosition) {
  35886. this.position.copyFrom(newPosition);
  35887. };
  35888. return DecimationVertex;
  35889. })();
  35890. BABYLON.DecimationVertex = DecimationVertex;
  35891. var QuadraticMatrix = (function () {
  35892. function QuadraticMatrix(data) {
  35893. this.data = new Array(10);
  35894. for (var i = 0; i < 10; ++i) {
  35895. if (data && data[i]) {
  35896. this.data[i] = data[i];
  35897. }
  35898. else {
  35899. this.data[i] = 0;
  35900. }
  35901. }
  35902. }
  35903. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  35904. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  35905. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  35906. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  35907. return det;
  35908. };
  35909. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  35910. for (var i = 0; i < 10; ++i) {
  35911. this.data[i] += matrix.data[i];
  35912. }
  35913. };
  35914. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  35915. for (var i = 0; i < 10; ++i) {
  35916. this.data[i] += data[i];
  35917. }
  35918. };
  35919. QuadraticMatrix.prototype.add = function (matrix) {
  35920. var m = new QuadraticMatrix();
  35921. for (var i = 0; i < 10; ++i) {
  35922. m.data[i] = this.data[i] + matrix.data[i];
  35923. }
  35924. return m;
  35925. };
  35926. QuadraticMatrix.FromData = function (a, b, c, d) {
  35927. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  35928. };
  35929. //returning an array to avoid garbage collection
  35930. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  35931. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  35932. };
  35933. return QuadraticMatrix;
  35934. })();
  35935. BABYLON.QuadraticMatrix = QuadraticMatrix;
  35936. var Reference = (function () {
  35937. function Reference(vertexId, triangleId) {
  35938. this.vertexId = vertexId;
  35939. this.triangleId = triangleId;
  35940. }
  35941. return Reference;
  35942. })();
  35943. BABYLON.Reference = Reference;
  35944. /**
  35945. * An implementation of the Quadratic Error simplification algorithm.
  35946. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  35947. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  35948. * @author RaananW
  35949. */
  35950. var QuadraticErrorSimplification = (function () {
  35951. function QuadraticErrorSimplification(_mesh) {
  35952. this._mesh = _mesh;
  35953. this.initialized = false;
  35954. this.syncIterations = 5000;
  35955. this.aggressiveness = 7;
  35956. this.decimationIterations = 100;
  35957. this.boundingBoxEpsilon = BABYLON.Epsilon;
  35958. }
  35959. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  35960. var _this = this;
  35961. this.initDecimatedMesh();
  35962. //iterating through the submeshes array, one after the other.
  35963. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  35964. _this.initWithMesh(loop.index, function () {
  35965. _this.runDecimation(settings, loop.index, function () {
  35966. loop.executeNext();
  35967. });
  35968. }, settings.optimizeMesh);
  35969. }, function () {
  35970. setTimeout(function () {
  35971. successCallback(_this._reconstructedMesh);
  35972. }, 0);
  35973. });
  35974. };
  35975. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  35976. var _this = this;
  35977. var gCount = 0;
  35978. triangle.vertices.forEach(function (vertex) {
  35979. var count = 0;
  35980. var vPos = vertex.position;
  35981. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  35982. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  35983. ++count;
  35984. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  35985. ++count;
  35986. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  35987. ++count;
  35988. if (count > 1) {
  35989. ++gCount;
  35990. }
  35991. ;
  35992. });
  35993. if (gCount > 1) {
  35994. console.log(triangle, gCount);
  35995. }
  35996. return gCount > 1;
  35997. };
  35998. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  35999. var _this = this;
  36000. var targetCount = ~~(this.triangles.length * settings.quality);
  36001. var deletedTriangles = 0;
  36002. var triangleCount = this.triangles.length;
  36003. var iterationFunction = function (iteration, callback) {
  36004. setTimeout(function () {
  36005. if (iteration % 5 === 0) {
  36006. _this.updateMesh(iteration === 0);
  36007. }
  36008. for (var i = 0; i < _this.triangles.length; ++i) {
  36009. _this.triangles[i].isDirty = false;
  36010. }
  36011. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  36012. var trianglesIterator = function (i) {
  36013. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  36014. var t = _this.triangles[tIdx];
  36015. if (!t)
  36016. return;
  36017. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  36018. return;
  36019. }
  36020. for (var j = 0; j < 3; ++j) {
  36021. if (t.error[j] < threshold) {
  36022. var deleted0 = [];
  36023. var deleted1 = [];
  36024. var v0 = t.vertices[j];
  36025. var v1 = t.vertices[(j + 1) % 3];
  36026. if (v0.isBorder || v1.isBorder)
  36027. continue;
  36028. var p = BABYLON.Vector3.Zero();
  36029. var n = BABYLON.Vector3.Zero();
  36030. var uv = BABYLON.Vector2.Zero();
  36031. var color = new BABYLON.Color4(0, 0, 0, 1);
  36032. _this.calculateError(v0, v1, p, n, uv, color);
  36033. var delTr = [];
  36034. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  36035. continue;
  36036. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  36037. continue;
  36038. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  36039. continue;
  36040. var uniqueArray = [];
  36041. delTr.forEach(function (deletedT) {
  36042. if (uniqueArray.indexOf(deletedT) === -1) {
  36043. deletedT.deletePending = true;
  36044. uniqueArray.push(deletedT);
  36045. }
  36046. });
  36047. if (uniqueArray.length % 2 !== 0) {
  36048. continue;
  36049. }
  36050. v0.q = v1.q.add(v0.q);
  36051. v0.updatePosition(p);
  36052. var tStart = _this.references.length;
  36053. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  36054. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  36055. var tCount = _this.references.length - tStart;
  36056. if (tCount <= v0.triangleCount) {
  36057. if (tCount) {
  36058. for (var c = 0; c < tCount; c++) {
  36059. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  36060. }
  36061. }
  36062. }
  36063. else {
  36064. v0.triangleStart = tStart;
  36065. }
  36066. v0.triangleCount = tCount;
  36067. break;
  36068. }
  36069. }
  36070. };
  36071. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  36072. }, 0);
  36073. };
  36074. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  36075. if (triangleCount - deletedTriangles <= targetCount)
  36076. loop.breakLoop();
  36077. else {
  36078. iterationFunction(loop.index, function () {
  36079. loop.executeNext();
  36080. });
  36081. }
  36082. }, function () {
  36083. setTimeout(function () {
  36084. //reconstruct this part of the mesh
  36085. _this.reconstructMesh(submeshIndex);
  36086. successCallback();
  36087. }, 0);
  36088. });
  36089. };
  36090. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  36091. var _this = this;
  36092. this.vertices = [];
  36093. this.triangles = [];
  36094. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36095. var indices = this._mesh.getIndices();
  36096. var submesh = this._mesh.subMeshes[submeshIndex];
  36097. var findInVertices = function (positionToSearch) {
  36098. if (optimizeMesh) {
  36099. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  36100. if (_this.vertices[ii].position.equals(positionToSearch)) {
  36101. return _this.vertices[ii];
  36102. }
  36103. }
  36104. }
  36105. return null;
  36106. };
  36107. var vertexReferences = [];
  36108. var vertexInit = function (i) {
  36109. var offset = i + submesh.verticesStart;
  36110. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  36111. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  36112. vertex.originalOffsets.push(offset);
  36113. if (vertex.id === _this.vertices.length) {
  36114. _this.vertices.push(vertex);
  36115. }
  36116. vertexReferences.push(vertex.id);
  36117. };
  36118. //var totalVertices = mesh.getTotalVertices();
  36119. var totalVertices = submesh.verticesCount;
  36120. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  36121. var indicesInit = function (i) {
  36122. var offset = (submesh.indexStart / 3) + i;
  36123. var pos = (offset * 3);
  36124. var i0 = indices[pos + 0];
  36125. var i1 = indices[pos + 1];
  36126. var i2 = indices[pos + 2];
  36127. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  36128. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  36129. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  36130. var triangle = new DecimationTriangle([v0, v1, v2]);
  36131. triangle.originalOffset = pos;
  36132. _this.triangles.push(triangle);
  36133. };
  36134. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  36135. _this.init(callback);
  36136. });
  36137. });
  36138. };
  36139. QuadraticErrorSimplification.prototype.init = function (callback) {
  36140. var _this = this;
  36141. var triangleInit1 = function (i) {
  36142. var t = _this.triangles[i];
  36143. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  36144. for (var j = 0; j < 3; j++) {
  36145. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  36146. }
  36147. };
  36148. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  36149. var triangleInit2 = function (i) {
  36150. var t = _this.triangles[i];
  36151. for (var j = 0; j < 3; ++j) {
  36152. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  36153. }
  36154. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  36155. };
  36156. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  36157. _this.initialized = true;
  36158. callback();
  36159. });
  36160. });
  36161. };
  36162. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  36163. var newTriangles = [];
  36164. var i;
  36165. for (i = 0; i < this.vertices.length; ++i) {
  36166. this.vertices[i].triangleCount = 0;
  36167. }
  36168. var t;
  36169. var j;
  36170. for (i = 0; i < this.triangles.length; ++i) {
  36171. if (!this.triangles[i].deleted) {
  36172. t = this.triangles[i];
  36173. for (j = 0; j < 3; ++j) {
  36174. t.vertices[j].triangleCount = 1;
  36175. }
  36176. newTriangles.push(t);
  36177. }
  36178. }
  36179. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  36180. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  36181. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  36182. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  36183. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36184. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36185. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36186. var vertexCount = 0;
  36187. for (i = 0; i < this.vertices.length; ++i) {
  36188. var vertex = this.vertices[i];
  36189. vertex.id = vertexCount;
  36190. if (vertex.triangleCount) {
  36191. vertex.originalOffsets.forEach(function (originalOffset) {
  36192. newPositionData.push(vertex.position.x);
  36193. newPositionData.push(vertex.position.y);
  36194. newPositionData.push(vertex.position.z);
  36195. newNormalData.push(normalData[originalOffset * 3]);
  36196. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  36197. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  36198. if (uvs && uvs.length) {
  36199. newUVsData.push(uvs[(originalOffset * 2)]);
  36200. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  36201. }
  36202. else if (colorsData && colorsData.length) {
  36203. newColorsData.push(colorsData[(originalOffset * 4)]);
  36204. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  36205. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  36206. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  36207. }
  36208. ++vertexCount;
  36209. });
  36210. }
  36211. }
  36212. var startingIndex = this._reconstructedMesh.getTotalIndices();
  36213. var startingVertex = this._reconstructedMesh.getTotalVertices();
  36214. var submeshesArray = this._reconstructedMesh.subMeshes;
  36215. this._reconstructedMesh.subMeshes = [];
  36216. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  36217. var originalIndices = this._mesh.getIndices();
  36218. for (i = 0; i < newTriangles.length; ++i) {
  36219. t = newTriangles[i]; //now get the new referencing point for each vertex
  36220. [0, 1, 2].forEach(function (idx) {
  36221. var id = originalIndices[t.originalOffset + idx];
  36222. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  36223. if (offset < 0)
  36224. offset = 0;
  36225. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  36226. });
  36227. }
  36228. //overwriting the old vertex buffers and indices.
  36229. this._reconstructedMesh.setIndices(newIndicesArray);
  36230. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  36231. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  36232. if (newUVsData.length > 0)
  36233. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  36234. if (newColorsData.length > 0)
  36235. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  36236. //create submesh
  36237. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  36238. if (submeshIndex > 0) {
  36239. this._reconstructedMesh.subMeshes = [];
  36240. submeshesArray.forEach(function (submesh) {
  36241. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  36242. });
  36243. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  36244. }
  36245. };
  36246. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  36247. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  36248. this._reconstructedMesh.material = this._mesh.material;
  36249. this._reconstructedMesh.parent = this._mesh.parent;
  36250. this._reconstructedMesh.isVisible = false;
  36251. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  36252. };
  36253. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  36254. for (var i = 0; i < vertex1.triangleCount; ++i) {
  36255. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  36256. if (t.deleted)
  36257. continue;
  36258. var s = this.references[vertex1.triangleStart + i].vertexId;
  36259. var v1 = t.vertices[(s + 1) % 3];
  36260. var v2 = t.vertices[(s + 2) % 3];
  36261. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  36262. deletedArray[i] = true;
  36263. delTr.push(t);
  36264. continue;
  36265. }
  36266. var d1 = v1.position.subtract(point);
  36267. d1 = d1.normalize();
  36268. var d2 = v2.position.subtract(point);
  36269. d2 = d2.normalize();
  36270. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  36271. return true;
  36272. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  36273. deletedArray[i] = false;
  36274. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  36275. return true;
  36276. }
  36277. return false;
  36278. };
  36279. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  36280. var newDeleted = deletedTriangles;
  36281. for (var i = 0; i < vertex.triangleCount; ++i) {
  36282. var ref = this.references[vertex.triangleStart + i];
  36283. var t = this.triangles[ref.triangleId];
  36284. if (t.deleted)
  36285. continue;
  36286. if (deletedArray[i] && t.deletePending) {
  36287. t.deleted = true;
  36288. newDeleted++;
  36289. continue;
  36290. }
  36291. t.vertices[ref.vertexId] = origVertex;
  36292. t.isDirty = true;
  36293. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  36294. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  36295. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  36296. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  36297. this.references.push(ref);
  36298. }
  36299. return newDeleted;
  36300. };
  36301. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  36302. for (var i = 0; i < this.vertices.length; ++i) {
  36303. var vCount = [];
  36304. var vId = [];
  36305. var v = this.vertices[i];
  36306. var j;
  36307. for (j = 0; j < v.triangleCount; ++j) {
  36308. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  36309. for (var ii = 0; ii < 3; ii++) {
  36310. var ofs = 0;
  36311. var vv = triangle.vertices[ii];
  36312. while (ofs < vCount.length) {
  36313. if (vId[ofs] === vv.id)
  36314. break;
  36315. ++ofs;
  36316. }
  36317. if (ofs === vCount.length) {
  36318. vCount.push(1);
  36319. vId.push(vv.id);
  36320. }
  36321. else {
  36322. vCount[ofs]++;
  36323. }
  36324. }
  36325. }
  36326. for (j = 0; j < vCount.length; ++j) {
  36327. if (vCount[j] === 1) {
  36328. this.vertices[vId[j]].isBorder = true;
  36329. }
  36330. else {
  36331. this.vertices[vId[j]].isBorder = false;
  36332. }
  36333. }
  36334. }
  36335. };
  36336. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  36337. if (identifyBorders === void 0) { identifyBorders = false; }
  36338. var i;
  36339. if (!identifyBorders) {
  36340. var newTrianglesVector = [];
  36341. for (i = 0; i < this.triangles.length; ++i) {
  36342. if (!this.triangles[i].deleted) {
  36343. newTrianglesVector.push(this.triangles[i]);
  36344. }
  36345. }
  36346. this.triangles = newTrianglesVector;
  36347. }
  36348. for (i = 0; i < this.vertices.length; ++i) {
  36349. this.vertices[i].triangleCount = 0;
  36350. this.vertices[i].triangleStart = 0;
  36351. }
  36352. var t;
  36353. var j;
  36354. var v;
  36355. for (i = 0; i < this.triangles.length; ++i) {
  36356. t = this.triangles[i];
  36357. for (j = 0; j < 3; ++j) {
  36358. v = t.vertices[j];
  36359. v.triangleCount++;
  36360. }
  36361. }
  36362. var tStart = 0;
  36363. for (i = 0; i < this.vertices.length; ++i) {
  36364. this.vertices[i].triangleStart = tStart;
  36365. tStart += this.vertices[i].triangleCount;
  36366. this.vertices[i].triangleCount = 0;
  36367. }
  36368. var newReferences = new Array(this.triangles.length * 3);
  36369. for (i = 0; i < this.triangles.length; ++i) {
  36370. t = this.triangles[i];
  36371. for (j = 0; j < 3; ++j) {
  36372. v = t.vertices[j];
  36373. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  36374. v.triangleCount++;
  36375. }
  36376. }
  36377. this.references = newReferences;
  36378. if (identifyBorders) {
  36379. this.identifyBorder();
  36380. }
  36381. };
  36382. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  36383. var x = point.x;
  36384. var y = point.y;
  36385. var z = point.z;
  36386. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  36387. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  36388. };
  36389. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  36390. var q = vertex1.q.add(vertex2.q);
  36391. var border = vertex1.isBorder && vertex2.isBorder;
  36392. var error = 0;
  36393. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  36394. if (qDet !== 0 && !border) {
  36395. if (!pointResult) {
  36396. pointResult = BABYLON.Vector3.Zero();
  36397. }
  36398. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  36399. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  36400. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  36401. error = this.vertexError(q, pointResult);
  36402. }
  36403. else {
  36404. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  36405. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  36406. var error1 = this.vertexError(q, vertex1.position);
  36407. var error2 = this.vertexError(q, vertex2.position);
  36408. var error3 = this.vertexError(q, p3);
  36409. error = Math.min(error1, error2, error3);
  36410. if (error === error1) {
  36411. if (pointResult) {
  36412. pointResult.copyFrom(vertex1.position);
  36413. }
  36414. }
  36415. else if (error === error2) {
  36416. if (pointResult) {
  36417. pointResult.copyFrom(vertex2.position);
  36418. }
  36419. }
  36420. else {
  36421. if (pointResult) {
  36422. pointResult.copyFrom(p3);
  36423. }
  36424. }
  36425. }
  36426. return error;
  36427. };
  36428. return QuadraticErrorSimplification;
  36429. })();
  36430. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  36431. })(BABYLON || (BABYLON = {}));
  36432. var BABYLON;
  36433. (function (BABYLON) {
  36434. var serializedGeometries = [];
  36435. var serializeGeometry = function (geometry, serializationGeometries) {
  36436. if (serializedGeometries[geometry.id]) {
  36437. return;
  36438. }
  36439. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  36440. serializationGeometries.boxes.push(geometry.serialize());
  36441. }
  36442. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  36443. serializationGeometries.spheres.push(geometry.serialize());
  36444. }
  36445. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  36446. serializationGeometries.cylinders.push(geometry.serialize());
  36447. }
  36448. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  36449. serializationGeometries.toruses.push(geometry.serialize());
  36450. }
  36451. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  36452. serializationGeometries.grounds.push(geometry.serialize());
  36453. }
  36454. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  36455. serializationGeometries.planes.push(geometry.serialize());
  36456. }
  36457. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  36458. serializationGeometries.torusKnots.push(geometry.serialize());
  36459. }
  36460. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  36461. throw new Error("Unknown primitive type");
  36462. }
  36463. else {
  36464. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  36465. }
  36466. serializedGeometries[geometry.id] = true;
  36467. };
  36468. var serializeMesh = function (mesh, serializationScene) {
  36469. var serializationObject = {};
  36470. serializationObject.name = mesh.name;
  36471. serializationObject.id = mesh.id;
  36472. if (BABYLON.Tags.HasTags(mesh)) {
  36473. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  36474. }
  36475. serializationObject.position = mesh.position.asArray();
  36476. if (mesh.rotationQuaternion) {
  36477. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  36478. }
  36479. else if (mesh.rotation) {
  36480. serializationObject.rotation = mesh.rotation.asArray();
  36481. }
  36482. serializationObject.scaling = mesh.scaling.asArray();
  36483. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  36484. serializationObject.isEnabled = mesh.isEnabled();
  36485. serializationObject.isVisible = mesh.isVisible;
  36486. serializationObject.infiniteDistance = mesh.infiniteDistance;
  36487. serializationObject.pickable = mesh.isPickable;
  36488. serializationObject.receiveShadows = mesh.receiveShadows;
  36489. serializationObject.billboardMode = mesh.billboardMode;
  36490. serializationObject.visibility = mesh.visibility;
  36491. serializationObject.checkCollisions = mesh.checkCollisions;
  36492. // Parent
  36493. if (mesh.parent) {
  36494. serializationObject.parentId = mesh.parent.id;
  36495. }
  36496. // Geometry
  36497. var geometry = mesh._geometry;
  36498. if (geometry) {
  36499. var geometryId = geometry.id;
  36500. serializationObject.geometryId = geometryId;
  36501. if (!mesh.getScene().getGeometryByID(geometryId)) {
  36502. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  36503. serializeGeometry(geometry, serializationScene.geometries);
  36504. }
  36505. // SubMeshes
  36506. serializationObject.subMeshes = [];
  36507. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36508. var subMesh = mesh.subMeshes[subIndex];
  36509. serializationObject.subMeshes.push({
  36510. materialIndex: subMesh.materialIndex,
  36511. verticesStart: subMesh.verticesStart,
  36512. verticesCount: subMesh.verticesCount,
  36513. indexStart: subMesh.indexStart,
  36514. indexCount: subMesh.indexCount
  36515. });
  36516. }
  36517. }
  36518. // Material
  36519. if (mesh.material) {
  36520. serializationObject.materialId = mesh.material.id;
  36521. }
  36522. else {
  36523. mesh.material = null;
  36524. }
  36525. // Skeleton
  36526. if (mesh.skeleton) {
  36527. serializationObject.skeletonId = mesh.skeleton.id;
  36528. }
  36529. // Physics
  36530. //TODO implement correct serialization for physics impostors.
  36531. if (mesh.getPhysicsImpostor()) {
  36532. serializationObject.physicsMass = mesh.getPhysicsMass();
  36533. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  36534. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  36535. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  36536. }
  36537. // Instances
  36538. serializationObject.instances = [];
  36539. for (var index = 0; index < mesh.instances.length; index++) {
  36540. var instance = mesh.instances[index];
  36541. var serializationInstance = {
  36542. name: instance.name,
  36543. position: instance.position.asArray(),
  36544. scaling: instance.scaling.asArray()
  36545. };
  36546. if (instance.rotationQuaternion) {
  36547. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  36548. }
  36549. else if (instance.rotation) {
  36550. serializationInstance.rotation = instance.rotation.asArray();
  36551. }
  36552. serializationObject.instances.push(serializationInstance);
  36553. // Animations
  36554. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  36555. serializationInstance.ranges = instance.serializeAnimationRanges();
  36556. }
  36557. // Animations
  36558. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  36559. serializationObject.ranges = mesh.serializeAnimationRanges();
  36560. // Layer mask
  36561. serializationObject.layerMask = mesh.layerMask;
  36562. // Action Manager
  36563. if (mesh.actionManager) {
  36564. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  36565. }
  36566. return serializationObject;
  36567. };
  36568. var finalizeSingleMesh = function (mesh, serializationObject) {
  36569. //only works if the mesh is already loaded
  36570. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36571. //serialize material
  36572. if (mesh.material) {
  36573. if (mesh.material instanceof BABYLON.StandardMaterial) {
  36574. serializationObject.materials = serializationObject.materials || [];
  36575. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  36576. serializationObject.materials.push(mesh.material.serialize());
  36577. }
  36578. }
  36579. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  36580. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  36581. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  36582. serializationObject.multiMaterials.push(mesh.material.serialize());
  36583. }
  36584. }
  36585. }
  36586. //serialize geometry
  36587. var geometry = mesh._geometry;
  36588. if (geometry) {
  36589. if (!serializationObject.geometries) {
  36590. serializationObject.geometries = {};
  36591. serializationObject.geometries.boxes = [];
  36592. serializationObject.geometries.spheres = [];
  36593. serializationObject.geometries.cylinders = [];
  36594. serializationObject.geometries.toruses = [];
  36595. serializationObject.geometries.grounds = [];
  36596. serializationObject.geometries.planes = [];
  36597. serializationObject.geometries.torusKnots = [];
  36598. serializationObject.geometries.vertexData = [];
  36599. }
  36600. serializeGeometry(geometry, serializationObject.geometries);
  36601. }
  36602. // Skeletons
  36603. if (mesh.skeleton) {
  36604. serializationObject.skeletons = serializationObject.skeletons || [];
  36605. serializationObject.skeletons.push(mesh.skeleton.serialize());
  36606. }
  36607. //serialize the actual mesh
  36608. serializationObject.meshes = serializationObject.meshes || [];
  36609. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36610. }
  36611. };
  36612. var SceneSerializer = (function () {
  36613. function SceneSerializer() {
  36614. }
  36615. SceneSerializer.ClearCache = function () {
  36616. serializedGeometries = [];
  36617. };
  36618. SceneSerializer.Serialize = function (scene) {
  36619. var serializationObject = {};
  36620. // Scene
  36621. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  36622. serializationObject.autoClear = scene.autoClear;
  36623. serializationObject.clearColor = scene.clearColor.asArray();
  36624. serializationObject.ambientColor = scene.ambientColor.asArray();
  36625. serializationObject.gravity = scene.gravity.asArray();
  36626. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  36627. serializationObject.workerCollisions = scene.workerCollisions;
  36628. // Fog
  36629. if (scene.fogMode && scene.fogMode !== 0) {
  36630. serializationObject.fogMode = scene.fogMode;
  36631. serializationObject.fogColor = scene.fogColor.asArray();
  36632. serializationObject.fogStart = scene.fogStart;
  36633. serializationObject.fogEnd = scene.fogEnd;
  36634. serializationObject.fogDensity = scene.fogDensity;
  36635. }
  36636. //Physics
  36637. if (scene.isPhysicsEnabled()) {
  36638. serializationObject.physicsEnabled = true;
  36639. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  36640. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  36641. }
  36642. // Lights
  36643. serializationObject.lights = [];
  36644. var index;
  36645. var light;
  36646. for (index = 0; index < scene.lights.length; index++) {
  36647. light = scene.lights[index];
  36648. serializationObject.lights.push(light.serialize());
  36649. }
  36650. // Cameras
  36651. serializationObject.cameras = [];
  36652. for (index = 0; index < scene.cameras.length; index++) {
  36653. var camera = scene.cameras[index];
  36654. serializationObject.cameras.push(camera.serialize());
  36655. }
  36656. if (scene.activeCamera) {
  36657. serializationObject.activeCameraID = scene.activeCamera.id;
  36658. }
  36659. // Animations
  36660. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  36661. // Materials
  36662. serializationObject.materials = [];
  36663. serializationObject.multiMaterials = [];
  36664. var material;
  36665. for (index = 0; index < scene.materials.length; index++) {
  36666. material = scene.materials[index];
  36667. serializationObject.materials.push(material.serialize());
  36668. }
  36669. // MultiMaterials
  36670. serializationObject.multiMaterials = [];
  36671. for (index = 0; index < scene.multiMaterials.length; index++) {
  36672. var multiMaterial = scene.multiMaterials[index];
  36673. serializationObject.multiMaterials.push(multiMaterial.serialize());
  36674. }
  36675. // Skeletons
  36676. serializationObject.skeletons = [];
  36677. for (index = 0; index < scene.skeletons.length; index++) {
  36678. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  36679. }
  36680. // Geometries
  36681. serializationObject.geometries = {};
  36682. serializationObject.geometries.boxes = [];
  36683. serializationObject.geometries.spheres = [];
  36684. serializationObject.geometries.cylinders = [];
  36685. serializationObject.geometries.toruses = [];
  36686. serializationObject.geometries.grounds = [];
  36687. serializationObject.geometries.planes = [];
  36688. serializationObject.geometries.torusKnots = [];
  36689. serializationObject.geometries.vertexData = [];
  36690. serializedGeometries = [];
  36691. var geometries = scene.getGeometries();
  36692. for (index = 0; index < geometries.length; index++) {
  36693. var geometry = geometries[index];
  36694. if (geometry.isReady()) {
  36695. serializeGeometry(geometry, serializationObject.geometries);
  36696. }
  36697. }
  36698. // Meshes
  36699. serializationObject.meshes = [];
  36700. for (index = 0; index < scene.meshes.length; index++) {
  36701. var abstractMesh = scene.meshes[index];
  36702. if (abstractMesh instanceof BABYLON.Mesh) {
  36703. var mesh = abstractMesh;
  36704. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36705. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36706. }
  36707. }
  36708. }
  36709. // Particles Systems
  36710. serializationObject.particleSystems = [];
  36711. for (index = 0; index < scene.particleSystems.length; index++) {
  36712. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  36713. }
  36714. // Lens flares
  36715. serializationObject.lensFlareSystems = [];
  36716. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  36717. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  36718. }
  36719. // Shadows
  36720. serializationObject.shadowGenerators = [];
  36721. for (index = 0; index < scene.lights.length; index++) {
  36722. light = scene.lights[index];
  36723. if (light.getShadowGenerator()) {
  36724. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  36725. }
  36726. }
  36727. // Action Manager
  36728. if (scene.actionManager) {
  36729. serializationObject.actions = scene.actionManager.serialize("scene");
  36730. }
  36731. return serializationObject;
  36732. };
  36733. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  36734. if (withParents === void 0) { withParents = false; }
  36735. if (withChildren === void 0) { withChildren = false; }
  36736. var serializationObject = {};
  36737. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  36738. if (withParents || withChildren) {
  36739. //deliberate for loop! not for each, appended should be processed as well.
  36740. for (var i = 0; i < toSerialize.length; ++i) {
  36741. if (withChildren) {
  36742. toSerialize[i].getDescendants().forEach(function (node) {
  36743. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  36744. toSerialize.push(node);
  36745. }
  36746. });
  36747. }
  36748. //make sure the array doesn't contain the object already
  36749. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  36750. toSerialize.push(toSerialize[i].parent);
  36751. }
  36752. }
  36753. }
  36754. toSerialize.forEach(function (mesh) {
  36755. finalizeSingleMesh(mesh, serializationObject);
  36756. });
  36757. return serializationObject;
  36758. };
  36759. return SceneSerializer;
  36760. })();
  36761. BABYLON.SceneSerializer = SceneSerializer;
  36762. })(BABYLON || (BABYLON = {}));
  36763. var BABYLON;
  36764. (function (BABYLON) {
  36765. // Unique ID when we import meshes from Babylon to CSG
  36766. var currentCSGMeshId = 0;
  36767. // # class Vertex
  36768. // Represents a vertex of a polygon. Use your own vertex class instead of this
  36769. // one to provide additional features like texture coordinates and vertex
  36770. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  36771. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  36772. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  36773. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  36774. // is not used anywhere else.
  36775. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  36776. var Vertex = (function () {
  36777. function Vertex(pos, normal, uv) {
  36778. this.pos = pos;
  36779. this.normal = normal;
  36780. this.uv = uv;
  36781. }
  36782. Vertex.prototype.clone = function () {
  36783. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  36784. };
  36785. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  36786. // orientation of a polygon is flipped.
  36787. Vertex.prototype.flip = function () {
  36788. this.normal = this.normal.scale(-1);
  36789. };
  36790. // Create a new vertex between this vertex and `other` by linearly
  36791. // interpolating all properties using a parameter of `t`. Subclasses should
  36792. // override this to interpolate additional properties.
  36793. Vertex.prototype.interpolate = function (other, t) {
  36794. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  36795. };
  36796. return Vertex;
  36797. })();
  36798. // # class Plane
  36799. // Represents a plane in 3D space.
  36800. var Plane = (function () {
  36801. function Plane(normal, w) {
  36802. this.normal = normal;
  36803. this.w = w;
  36804. }
  36805. Plane.FromPoints = function (a, b, c) {
  36806. var v0 = c.subtract(a);
  36807. var v1 = b.subtract(a);
  36808. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  36809. return null;
  36810. }
  36811. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  36812. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  36813. };
  36814. Plane.prototype.clone = function () {
  36815. return new Plane(this.normal.clone(), this.w);
  36816. };
  36817. Plane.prototype.flip = function () {
  36818. this.normal.scaleInPlace(-1);
  36819. this.w = -this.w;
  36820. };
  36821. // Split `polygon` by this plane if needed, then put the polygon or polygon
  36822. // fragments in the appropriate lists. Coplanar polygons go into either
  36823. // `coplanarFront` or `coplanarBack` depending on their orientation with
  36824. // respect to this plane. Polygons in front or in back of this plane go into
  36825. // either `front` or `back`.
  36826. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  36827. var COPLANAR = 0;
  36828. var FRONT = 1;
  36829. var BACK = 2;
  36830. var SPANNING = 3;
  36831. // Classify each point as well as the entire polygon into one of the above
  36832. // four classes.
  36833. var polygonType = 0;
  36834. var types = [];
  36835. var i;
  36836. var t;
  36837. for (i = 0; i < polygon.vertices.length; i++) {
  36838. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  36839. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  36840. polygonType |= type;
  36841. types.push(type);
  36842. }
  36843. // Put the polygon in the correct list, splitting it when necessary.
  36844. switch (polygonType) {
  36845. case COPLANAR:
  36846. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  36847. break;
  36848. case FRONT:
  36849. front.push(polygon);
  36850. break;
  36851. case BACK:
  36852. back.push(polygon);
  36853. break;
  36854. case SPANNING:
  36855. var f = [], b = [];
  36856. for (i = 0; i < polygon.vertices.length; i++) {
  36857. var j = (i + 1) % polygon.vertices.length;
  36858. var ti = types[i], tj = types[j];
  36859. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  36860. if (ti !== BACK)
  36861. f.push(vi);
  36862. if (ti !== FRONT)
  36863. b.push(ti !== BACK ? vi.clone() : vi);
  36864. if ((ti | tj) === SPANNING) {
  36865. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  36866. var v = vi.interpolate(vj, t);
  36867. f.push(v);
  36868. b.push(v.clone());
  36869. }
  36870. }
  36871. var poly;
  36872. if (f.length >= 3) {
  36873. poly = new Polygon(f, polygon.shared);
  36874. if (poly.plane)
  36875. front.push(poly);
  36876. }
  36877. if (b.length >= 3) {
  36878. poly = new Polygon(b, polygon.shared);
  36879. if (poly.plane)
  36880. back.push(poly);
  36881. }
  36882. break;
  36883. }
  36884. };
  36885. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  36886. // point is on the plane.
  36887. Plane.EPSILON = 1e-5;
  36888. return Plane;
  36889. })();
  36890. // # class Polygon
  36891. // Represents a convex polygon. The vertices used to initialize a polygon must
  36892. // be coplanar and form a convex loop.
  36893. //
  36894. // Each convex polygon has a `shared` property, which is shared between all
  36895. // polygons that are clones of each other or were split from the same polygon.
  36896. // This can be used to define per-polygon properties (such as surface color).
  36897. var Polygon = (function () {
  36898. function Polygon(vertices, shared) {
  36899. this.vertices = vertices;
  36900. this.shared = shared;
  36901. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  36902. }
  36903. Polygon.prototype.clone = function () {
  36904. var vertices = this.vertices.map(function (v) { return v.clone(); });
  36905. return new Polygon(vertices, this.shared);
  36906. };
  36907. Polygon.prototype.flip = function () {
  36908. this.vertices.reverse().map(function (v) { v.flip(); });
  36909. this.plane.flip();
  36910. };
  36911. return Polygon;
  36912. })();
  36913. // # class Node
  36914. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  36915. // by picking a polygon to split along. That polygon (and all other coplanar
  36916. // polygons) are added directly to that node and the other polygons are added to
  36917. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  36918. // no distinction between internal and leaf nodes.
  36919. var Node = (function () {
  36920. function Node(polygons) {
  36921. this.plane = null;
  36922. this.front = null;
  36923. this.back = null;
  36924. this.polygons = [];
  36925. if (polygons) {
  36926. this.build(polygons);
  36927. }
  36928. }
  36929. Node.prototype.clone = function () {
  36930. var node = new Node();
  36931. node.plane = this.plane && this.plane.clone();
  36932. node.front = this.front && this.front.clone();
  36933. node.back = this.back && this.back.clone();
  36934. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  36935. return node;
  36936. };
  36937. // Convert solid space to empty space and empty space to solid space.
  36938. Node.prototype.invert = function () {
  36939. for (var i = 0; i < this.polygons.length; i++) {
  36940. this.polygons[i].flip();
  36941. }
  36942. if (this.plane) {
  36943. this.plane.flip();
  36944. }
  36945. if (this.front) {
  36946. this.front.invert();
  36947. }
  36948. if (this.back) {
  36949. this.back.invert();
  36950. }
  36951. var temp = this.front;
  36952. this.front = this.back;
  36953. this.back = temp;
  36954. };
  36955. // Recursively remove all polygons in `polygons` that are inside this BSP
  36956. // tree.
  36957. Node.prototype.clipPolygons = function (polygons) {
  36958. if (!this.plane)
  36959. return polygons.slice();
  36960. var front = [], back = [];
  36961. for (var i = 0; i < polygons.length; i++) {
  36962. this.plane.splitPolygon(polygons[i], front, back, front, back);
  36963. }
  36964. if (this.front) {
  36965. front = this.front.clipPolygons(front);
  36966. }
  36967. if (this.back) {
  36968. back = this.back.clipPolygons(back);
  36969. }
  36970. else {
  36971. back = [];
  36972. }
  36973. return front.concat(back);
  36974. };
  36975. // Remove all polygons in this BSP tree that are inside the other BSP tree
  36976. // `bsp`.
  36977. Node.prototype.clipTo = function (bsp) {
  36978. this.polygons = bsp.clipPolygons(this.polygons);
  36979. if (this.front)
  36980. this.front.clipTo(bsp);
  36981. if (this.back)
  36982. this.back.clipTo(bsp);
  36983. };
  36984. // Return a list of all polygons in this BSP tree.
  36985. Node.prototype.allPolygons = function () {
  36986. var polygons = this.polygons.slice();
  36987. if (this.front)
  36988. polygons = polygons.concat(this.front.allPolygons());
  36989. if (this.back)
  36990. polygons = polygons.concat(this.back.allPolygons());
  36991. return polygons;
  36992. };
  36993. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  36994. // new polygons are filtered down to the bottom of the tree and become new
  36995. // nodes there. Each set of polygons is partitioned using the first polygon
  36996. // (no heuristic is used to pick a good split).
  36997. Node.prototype.build = function (polygons) {
  36998. if (!polygons.length)
  36999. return;
  37000. if (!this.plane)
  37001. this.plane = polygons[0].plane.clone();
  37002. var front = [], back = [];
  37003. for (var i = 0; i < polygons.length; i++) {
  37004. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  37005. }
  37006. if (front.length) {
  37007. if (!this.front)
  37008. this.front = new Node();
  37009. this.front.build(front);
  37010. }
  37011. if (back.length) {
  37012. if (!this.back)
  37013. this.back = new Node();
  37014. this.back.build(back);
  37015. }
  37016. };
  37017. return Node;
  37018. })();
  37019. var CSG = (function () {
  37020. function CSG() {
  37021. this.polygons = new Array();
  37022. }
  37023. // Convert BABYLON.Mesh to BABYLON.CSG
  37024. CSG.FromMesh = function (mesh) {
  37025. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  37026. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  37027. if (mesh instanceof BABYLON.Mesh) {
  37028. mesh.computeWorldMatrix(true);
  37029. matrix = mesh.getWorldMatrix();
  37030. meshPosition = mesh.position.clone();
  37031. meshRotation = mesh.rotation.clone();
  37032. if (mesh.rotationQuaternion) {
  37033. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  37034. }
  37035. meshScaling = mesh.scaling.clone();
  37036. }
  37037. else {
  37038. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  37039. }
  37040. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37041. var subMeshes = mesh.subMeshes;
  37042. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  37043. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  37044. vertices = [];
  37045. for (var j = 0; j < 3; j++) {
  37046. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  37047. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  37048. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  37049. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  37050. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  37051. vertex = new Vertex(position, normal, uv);
  37052. vertices.push(vertex);
  37053. }
  37054. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  37055. // To handle the case of degenerated triangle
  37056. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  37057. if (polygon.plane)
  37058. polygons.push(polygon);
  37059. }
  37060. }
  37061. var csg = CSG.FromPolygons(polygons);
  37062. csg.matrix = matrix;
  37063. csg.position = meshPosition;
  37064. csg.rotation = meshRotation;
  37065. csg.scaling = meshScaling;
  37066. csg.rotationQuaternion = meshRotationQuaternion;
  37067. currentCSGMeshId++;
  37068. return csg;
  37069. };
  37070. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  37071. CSG.FromPolygons = function (polygons) {
  37072. var csg = new CSG();
  37073. csg.polygons = polygons;
  37074. return csg;
  37075. };
  37076. CSG.prototype.clone = function () {
  37077. var csg = new CSG();
  37078. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  37079. csg.copyTransformAttributes(this);
  37080. return csg;
  37081. };
  37082. CSG.prototype.toPolygons = function () {
  37083. return this.polygons;
  37084. };
  37085. CSG.prototype.union = function (csg) {
  37086. var a = new Node(this.clone().polygons);
  37087. var b = new Node(csg.clone().polygons);
  37088. a.clipTo(b);
  37089. b.clipTo(a);
  37090. b.invert();
  37091. b.clipTo(a);
  37092. b.invert();
  37093. a.build(b.allPolygons());
  37094. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  37095. };
  37096. CSG.prototype.unionInPlace = function (csg) {
  37097. var a = new Node(this.polygons);
  37098. var b = new Node(csg.polygons);
  37099. a.clipTo(b);
  37100. b.clipTo(a);
  37101. b.invert();
  37102. b.clipTo(a);
  37103. b.invert();
  37104. a.build(b.allPolygons());
  37105. this.polygons = a.allPolygons();
  37106. };
  37107. CSG.prototype.subtract = function (csg) {
  37108. var a = new Node(this.clone().polygons);
  37109. var b = new Node(csg.clone().polygons);
  37110. a.invert();
  37111. a.clipTo(b);
  37112. b.clipTo(a);
  37113. b.invert();
  37114. b.clipTo(a);
  37115. b.invert();
  37116. a.build(b.allPolygons());
  37117. a.invert();
  37118. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  37119. };
  37120. CSG.prototype.subtractInPlace = function (csg) {
  37121. var a = new Node(this.polygons);
  37122. var b = new Node(csg.polygons);
  37123. a.invert();
  37124. a.clipTo(b);
  37125. b.clipTo(a);
  37126. b.invert();
  37127. b.clipTo(a);
  37128. b.invert();
  37129. a.build(b.allPolygons());
  37130. a.invert();
  37131. this.polygons = a.allPolygons();
  37132. };
  37133. CSG.prototype.intersect = function (csg) {
  37134. var a = new Node(this.clone().polygons);
  37135. var b = new Node(csg.clone().polygons);
  37136. a.invert();
  37137. b.clipTo(a);
  37138. b.invert();
  37139. a.clipTo(b);
  37140. b.clipTo(a);
  37141. a.build(b.allPolygons());
  37142. a.invert();
  37143. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  37144. };
  37145. CSG.prototype.intersectInPlace = function (csg) {
  37146. var a = new Node(this.polygons);
  37147. var b = new Node(csg.polygons);
  37148. a.invert();
  37149. b.clipTo(a);
  37150. b.invert();
  37151. a.clipTo(b);
  37152. b.clipTo(a);
  37153. a.build(b.allPolygons());
  37154. a.invert();
  37155. this.polygons = a.allPolygons();
  37156. };
  37157. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  37158. // not modified.
  37159. CSG.prototype.inverse = function () {
  37160. var csg = this.clone();
  37161. csg.inverseInPlace();
  37162. return csg;
  37163. };
  37164. CSG.prototype.inverseInPlace = function () {
  37165. this.polygons.map(function (p) { p.flip(); });
  37166. };
  37167. // This is used to keep meshes transformations so they can be restored
  37168. // when we build back a Babylon Mesh
  37169. // NB : All CSG operations are performed in world coordinates
  37170. CSG.prototype.copyTransformAttributes = function (csg) {
  37171. this.matrix = csg.matrix;
  37172. this.position = csg.position;
  37173. this.rotation = csg.rotation;
  37174. this.scaling = csg.scaling;
  37175. this.rotationQuaternion = csg.rotationQuaternion;
  37176. return this;
  37177. };
  37178. // Build Raw mesh from CSG
  37179. // Coordinates here are in world space
  37180. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  37181. var matrix = this.matrix.clone();
  37182. matrix.invert();
  37183. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  37184. if (keepSubMeshes) {
  37185. // Sort Polygons, since subMeshes are indices range
  37186. polygons.sort(function (a, b) {
  37187. if (a.shared.meshId === b.shared.meshId) {
  37188. return a.shared.subMeshId - b.shared.subMeshId;
  37189. }
  37190. else {
  37191. return a.shared.meshId - b.shared.meshId;
  37192. }
  37193. });
  37194. }
  37195. for (var i = 0, il = polygons.length; i < il; i++) {
  37196. polygon = polygons[i];
  37197. // Building SubMeshes
  37198. if (!subMesh_dict[polygon.shared.meshId]) {
  37199. subMesh_dict[polygon.shared.meshId] = {};
  37200. }
  37201. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  37202. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  37203. indexStart: +Infinity,
  37204. indexEnd: -Infinity,
  37205. materialIndex: polygon.shared.materialIndex
  37206. };
  37207. }
  37208. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  37209. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  37210. polygonIndices[0] = 0;
  37211. polygonIndices[1] = j - 1;
  37212. polygonIndices[2] = j;
  37213. for (var k = 0; k < 3; k++) {
  37214. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  37215. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  37216. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  37217. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  37218. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  37219. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  37220. // Check if 2 points can be merged
  37221. if (!(typeof vertex_idx !== 'undefined' &&
  37222. normals[vertex_idx * 3] === localNormal.x &&
  37223. normals[vertex_idx * 3 + 1] === localNormal.y &&
  37224. normals[vertex_idx * 3 + 2] === localNormal.z &&
  37225. uvs[vertex_idx * 2] === uv.x &&
  37226. uvs[vertex_idx * 2 + 1] === uv.y)) {
  37227. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  37228. uvs.push(uv.x, uv.y);
  37229. normals.push(normal.x, normal.y, normal.z);
  37230. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  37231. }
  37232. indices.push(vertex_idx);
  37233. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  37234. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  37235. currentIndex++;
  37236. }
  37237. }
  37238. }
  37239. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  37240. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  37241. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  37242. mesh.setIndices(indices);
  37243. if (keepSubMeshes) {
  37244. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  37245. var materialIndexOffset = 0, materialMaxIndex;
  37246. mesh.subMeshes = new Array();
  37247. for (var m in subMesh_dict) {
  37248. materialMaxIndex = -1;
  37249. for (var sm in subMesh_dict[m]) {
  37250. subMesh_obj = subMesh_dict[m][sm];
  37251. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  37252. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  37253. }
  37254. materialIndexOffset += ++materialMaxIndex;
  37255. }
  37256. }
  37257. return mesh;
  37258. };
  37259. // Build Mesh from CSG taking material and transforms into account
  37260. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  37261. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  37262. mesh.material = material;
  37263. mesh.position.copyFrom(this.position);
  37264. mesh.rotation.copyFrom(this.rotation);
  37265. if (this.rotationQuaternion) {
  37266. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  37267. }
  37268. mesh.scaling.copyFrom(this.scaling);
  37269. mesh.computeWorldMatrix(true);
  37270. return mesh;
  37271. };
  37272. return CSG;
  37273. })();
  37274. BABYLON.CSG = CSG;
  37275. })(BABYLON || (BABYLON = {}));
  37276. var BABYLON;
  37277. (function (BABYLON) {
  37278. var VRDistortionCorrectionPostProcess = (function (_super) {
  37279. __extends(VRDistortionCorrectionPostProcess, _super);
  37280. //ANY
  37281. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  37282. var _this = this;
  37283. _super.call(this, name, "vrDistortionCorrection", [
  37284. 'LensCenter',
  37285. 'Scale',
  37286. 'ScaleIn',
  37287. 'HmdWarpParam'
  37288. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  37289. this._isRightEye = isRightEye;
  37290. this._distortionFactors = vrMetrics.distortionK;
  37291. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  37292. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  37293. this.onSizeChanged = function () {
  37294. _this.aspectRatio = _this.width * .5 / _this.height;
  37295. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  37296. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  37297. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  37298. };
  37299. this.onApply = function (effect) {
  37300. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  37301. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  37302. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  37303. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  37304. };
  37305. }
  37306. return VRDistortionCorrectionPostProcess;
  37307. })(BABYLON.PostProcess);
  37308. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  37309. })(BABYLON || (BABYLON = {}));
  37310. // Mainly based on these 2 articles :
  37311. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  37312. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  37313. var BABYLON;
  37314. (function (BABYLON) {
  37315. (function (JoystickAxis) {
  37316. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  37317. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  37318. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  37319. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  37320. var JoystickAxis = BABYLON.JoystickAxis;
  37321. var VirtualJoystick = (function () {
  37322. function VirtualJoystick(leftJoystick) {
  37323. var _this = this;
  37324. if (leftJoystick) {
  37325. this._leftJoystick = true;
  37326. }
  37327. else {
  37328. this._leftJoystick = false;
  37329. }
  37330. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  37331. VirtualJoystick._globalJoystickIndex++;
  37332. // By default left & right arrow keys are moving the X
  37333. // and up & down keys are moving the Y
  37334. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  37335. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  37336. this.reverseLeftRight = false;
  37337. this.reverseUpDown = false;
  37338. // collections of pointers
  37339. this._touches = new BABYLON.StringDictionary();
  37340. this.deltaPosition = BABYLON.Vector3.Zero();
  37341. this._joystickSensibility = 25;
  37342. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  37343. this._rotationSpeed = 25;
  37344. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  37345. this._rotateOnAxisRelativeToMesh = false;
  37346. this._onResize = function (evt) {
  37347. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  37348. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  37349. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  37350. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  37351. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  37352. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  37353. };
  37354. // injecting a canvas element on top of the canvas 3D game
  37355. if (!VirtualJoystick.vjCanvas) {
  37356. window.addEventListener("resize", this._onResize, false);
  37357. VirtualJoystick.vjCanvas = document.createElement("canvas");
  37358. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  37359. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  37360. VirtualJoystick.vjCanvas.width = window.innerWidth;
  37361. VirtualJoystick.vjCanvas.height = window.innerHeight;
  37362. VirtualJoystick.vjCanvas.style.width = "100%";
  37363. VirtualJoystick.vjCanvas.style.height = "100%";
  37364. VirtualJoystick.vjCanvas.style.position = "absolute";
  37365. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  37366. VirtualJoystick.vjCanvas.style.top = "0px";
  37367. VirtualJoystick.vjCanvas.style.left = "0px";
  37368. VirtualJoystick.vjCanvas.style.zIndex = "5";
  37369. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  37370. // Support for jQuery PEP polyfill
  37371. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  37372. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  37373. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  37374. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  37375. document.body.appendChild(VirtualJoystick.vjCanvas);
  37376. }
  37377. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  37378. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  37379. this.pressed = false;
  37380. // default joystick color
  37381. this._joystickColor = "cyan";
  37382. this._joystickPointerID = -1;
  37383. // current joystick position
  37384. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  37385. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  37386. // origin joystick position
  37387. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  37388. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  37389. this._onPointerDownHandlerRef = function (evt) {
  37390. _this._onPointerDown(evt);
  37391. };
  37392. this._onPointerMoveHandlerRef = function (evt) {
  37393. _this._onPointerMove(evt);
  37394. };
  37395. this._onPointerOutHandlerRef = function (evt) {
  37396. _this._onPointerUp(evt);
  37397. };
  37398. this._onPointerUpHandlerRef = function (evt) {
  37399. _this._onPointerUp(evt);
  37400. };
  37401. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  37402. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  37403. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  37404. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  37405. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  37406. evt.preventDefault(); // Disables system menu
  37407. }, false);
  37408. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  37409. }
  37410. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  37411. this._joystickSensibility = newJoystickSensibility;
  37412. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  37413. };
  37414. VirtualJoystick.prototype._onPointerDown = function (e) {
  37415. var positionOnScreenCondition;
  37416. e.preventDefault();
  37417. if (this._leftJoystick === true) {
  37418. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  37419. }
  37420. else {
  37421. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  37422. }
  37423. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  37424. // First contact will be dedicated to the virtual joystick
  37425. this._joystickPointerID = e.pointerId;
  37426. this._joystickPointerStartPos.x = e.clientX;
  37427. this._joystickPointerStartPos.y = e.clientY;
  37428. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  37429. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  37430. this._deltaJoystickVector.x = 0;
  37431. this._deltaJoystickVector.y = 0;
  37432. this.pressed = true;
  37433. this._touches.add(e.pointerId.toString(), e);
  37434. }
  37435. else {
  37436. // You can only trigger the action buttons with a joystick declared
  37437. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  37438. this._action();
  37439. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  37440. }
  37441. }
  37442. };
  37443. VirtualJoystick.prototype._onPointerMove = function (e) {
  37444. // If the current pointer is the one associated to the joystick (first touch contact)
  37445. if (this._joystickPointerID == e.pointerId) {
  37446. this._joystickPointerPos.x = e.clientX;
  37447. this._joystickPointerPos.y = e.clientY;
  37448. this._deltaJoystickVector = this._joystickPointerPos.clone();
  37449. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  37450. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  37451. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  37452. switch (this._axisTargetedByLeftAndRight) {
  37453. case JoystickAxis.X:
  37454. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  37455. break;
  37456. case JoystickAxis.Y:
  37457. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  37458. break;
  37459. case JoystickAxis.Z:
  37460. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  37461. break;
  37462. }
  37463. var directionUpDown = this.reverseUpDown ? 1 : -1;
  37464. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  37465. switch (this._axisTargetedByUpAndDown) {
  37466. case JoystickAxis.X:
  37467. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  37468. break;
  37469. case JoystickAxis.Y:
  37470. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  37471. break;
  37472. case JoystickAxis.Z:
  37473. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  37474. break;
  37475. }
  37476. }
  37477. else {
  37478. var data = this._touches.get(e.pointerId.toString());
  37479. if (data) {
  37480. data.x = e.clientX;
  37481. data.y = e.clientY;
  37482. }
  37483. }
  37484. };
  37485. VirtualJoystick.prototype._onPointerUp = function (e) {
  37486. if (this._joystickPointerID == e.pointerId) {
  37487. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  37488. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  37489. this._joystickPointerID = -1;
  37490. this.pressed = false;
  37491. }
  37492. else {
  37493. var touch = this._touches.get(e.pointerId.toString());
  37494. if (touch) {
  37495. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  37496. }
  37497. }
  37498. this._deltaJoystickVector.x = 0;
  37499. this._deltaJoystickVector.y = 0;
  37500. this._touches.remove(e.pointerId.toString());
  37501. };
  37502. /**
  37503. * Change the color of the virtual joystick
  37504. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  37505. */
  37506. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  37507. this._joystickColor = newColor;
  37508. };
  37509. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  37510. this._action = action;
  37511. };
  37512. // Define which axis you'd like to control for left & right
  37513. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  37514. switch (axis) {
  37515. case JoystickAxis.X:
  37516. case JoystickAxis.Y:
  37517. case JoystickAxis.Z:
  37518. this._axisTargetedByLeftAndRight = axis;
  37519. break;
  37520. default:
  37521. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  37522. break;
  37523. }
  37524. };
  37525. // Define which axis you'd like to control for up & down
  37526. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  37527. switch (axis) {
  37528. case JoystickAxis.X:
  37529. case JoystickAxis.Y:
  37530. case JoystickAxis.Z:
  37531. this._axisTargetedByUpAndDown = axis;
  37532. break;
  37533. default:
  37534. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  37535. break;
  37536. }
  37537. };
  37538. VirtualJoystick.prototype._clearCanvas = function () {
  37539. if (this._leftJoystick) {
  37540. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  37541. }
  37542. else {
  37543. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  37544. }
  37545. };
  37546. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  37547. var _this = this;
  37548. if (this.pressed) {
  37549. this._touches.forEach(function (touch) {
  37550. if (touch.pointerId === _this._joystickPointerID) {
  37551. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  37552. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  37553. VirtualJoystick.vjCanvasContext.beginPath();
  37554. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  37555. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37556. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  37557. VirtualJoystick.vjCanvasContext.stroke();
  37558. VirtualJoystick.vjCanvasContext.closePath();
  37559. VirtualJoystick.vjCanvasContext.beginPath();
  37560. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37561. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  37562. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  37563. VirtualJoystick.vjCanvasContext.stroke();
  37564. VirtualJoystick.vjCanvasContext.closePath();
  37565. VirtualJoystick.vjCanvasContext.beginPath();
  37566. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37567. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  37568. VirtualJoystick.vjCanvasContext.stroke();
  37569. VirtualJoystick.vjCanvasContext.closePath();
  37570. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  37571. }
  37572. else {
  37573. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  37574. VirtualJoystick.vjCanvasContext.beginPath();
  37575. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  37576. VirtualJoystick.vjCanvasContext.beginPath();
  37577. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  37578. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  37579. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  37580. VirtualJoystick.vjCanvasContext.stroke();
  37581. VirtualJoystick.vjCanvasContext.closePath();
  37582. touch.prevX = touch.x;
  37583. touch.prevY = touch.y;
  37584. }
  37585. ;
  37586. });
  37587. }
  37588. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  37589. };
  37590. VirtualJoystick.prototype.releaseCanvas = function () {
  37591. if (VirtualJoystick.vjCanvas) {
  37592. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  37593. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  37594. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  37595. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  37596. window.removeEventListener("resize", this._onResize);
  37597. document.body.removeChild(VirtualJoystick.vjCanvas);
  37598. VirtualJoystick.vjCanvas = null;
  37599. }
  37600. };
  37601. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  37602. VirtualJoystick._globalJoystickIndex = 0;
  37603. return VirtualJoystick;
  37604. })();
  37605. BABYLON.VirtualJoystick = VirtualJoystick;
  37606. })(BABYLON || (BABYLON = {}));
  37607. var BABYLON;
  37608. (function (BABYLON) {
  37609. // We're mainly based on the logic defined into the FreeCamera code
  37610. var VirtualJoysticksCamera = (function (_super) {
  37611. __extends(VirtualJoysticksCamera, _super);
  37612. function VirtualJoysticksCamera(name, position, scene) {
  37613. _super.call(this, name, position, scene);
  37614. this.inputs.addVirtualJoystick();
  37615. }
  37616. return VirtualJoysticksCamera;
  37617. })(BABYLON.FreeCamera);
  37618. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  37619. })(BABYLON || (BABYLON = {}));
  37620. var BABYLON;
  37621. (function (BABYLON) {
  37622. var AnaglyphPostProcess = (function (_super) {
  37623. __extends(AnaglyphPostProcess, _super);
  37624. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37625. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  37626. }
  37627. return AnaglyphPostProcess;
  37628. })(BABYLON.PostProcess);
  37629. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  37630. })(BABYLON || (BABYLON = {}));
  37631. var BABYLON;
  37632. (function (BABYLON) {
  37633. var OutlineRenderer = (function () {
  37634. function OutlineRenderer(scene) {
  37635. this._scene = scene;
  37636. }
  37637. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  37638. var _this = this;
  37639. if (useOverlay === void 0) { useOverlay = false; }
  37640. var scene = this._scene;
  37641. var engine = this._scene.getEngine();
  37642. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37643. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  37644. return;
  37645. }
  37646. var mesh = subMesh.getRenderingMesh();
  37647. var material = subMesh.getMaterial();
  37648. engine.enableEffect(this._effect);
  37649. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  37650. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  37651. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  37652. // Bones
  37653. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37654. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37655. }
  37656. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  37657. // Alpha test
  37658. if (material && material.needAlphaTesting()) {
  37659. var alphaTexture = material.getAlphaTestTexture();
  37660. this._effect.setTexture("diffuseSampler", alphaTexture);
  37661. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37662. }
  37663. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  37664. };
  37665. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  37666. var defines = [];
  37667. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  37668. var mesh = subMesh.getMesh();
  37669. var material = subMesh.getMaterial();
  37670. // Alpha test
  37671. if (material && material.needAlphaTesting()) {
  37672. defines.push("#define ALPHATEST");
  37673. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37674. attribs.push(BABYLON.VertexBuffer.UVKind);
  37675. defines.push("#define UV1");
  37676. }
  37677. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37678. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37679. defines.push("#define UV2");
  37680. }
  37681. }
  37682. // Bones
  37683. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37684. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37685. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37686. if (mesh.numBoneInfluencers > 4) {
  37687. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37688. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37689. }
  37690. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37691. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37692. }
  37693. else {
  37694. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37695. }
  37696. // Instances
  37697. if (useInstances) {
  37698. defines.push("#define INSTANCES");
  37699. attribs.push("world0");
  37700. attribs.push("world1");
  37701. attribs.push("world2");
  37702. attribs.push("world3");
  37703. }
  37704. // Get correct effect
  37705. var join = defines.join("\n");
  37706. if (this._cachedDefines !== join) {
  37707. this._cachedDefines = join;
  37708. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  37709. }
  37710. return this._effect.isReady();
  37711. };
  37712. return OutlineRenderer;
  37713. })();
  37714. BABYLON.OutlineRenderer = OutlineRenderer;
  37715. })(BABYLON || (BABYLON = {}));
  37716. var BABYLON;
  37717. (function (BABYLON) {
  37718. var MeshAssetTask = (function () {
  37719. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  37720. this.name = name;
  37721. this.meshesNames = meshesNames;
  37722. this.rootUrl = rootUrl;
  37723. this.sceneFilename = sceneFilename;
  37724. this.isCompleted = false;
  37725. }
  37726. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37727. var _this = this;
  37728. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  37729. _this.loadedMeshes = meshes;
  37730. _this.loadedParticleSystems = particleSystems;
  37731. _this.loadedSkeletons = skeletons;
  37732. _this.isCompleted = true;
  37733. if (_this.onSuccess) {
  37734. _this.onSuccess(_this);
  37735. }
  37736. onSuccess();
  37737. }, null, function () {
  37738. if (_this.onError) {
  37739. _this.onError(_this);
  37740. }
  37741. onError();
  37742. });
  37743. };
  37744. return MeshAssetTask;
  37745. })();
  37746. BABYLON.MeshAssetTask = MeshAssetTask;
  37747. var TextFileAssetTask = (function () {
  37748. function TextFileAssetTask(name, url) {
  37749. this.name = name;
  37750. this.url = url;
  37751. this.isCompleted = false;
  37752. }
  37753. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37754. var _this = this;
  37755. BABYLON.Tools.LoadFile(this.url, function (data) {
  37756. _this.text = data;
  37757. _this.isCompleted = true;
  37758. if (_this.onSuccess) {
  37759. _this.onSuccess(_this);
  37760. }
  37761. onSuccess();
  37762. }, null, scene.database, false, function () {
  37763. if (_this.onError) {
  37764. _this.onError(_this);
  37765. }
  37766. onError();
  37767. });
  37768. };
  37769. return TextFileAssetTask;
  37770. })();
  37771. BABYLON.TextFileAssetTask = TextFileAssetTask;
  37772. var BinaryFileAssetTask = (function () {
  37773. function BinaryFileAssetTask(name, url) {
  37774. this.name = name;
  37775. this.url = url;
  37776. this.isCompleted = false;
  37777. }
  37778. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37779. var _this = this;
  37780. BABYLON.Tools.LoadFile(this.url, function (data) {
  37781. _this.data = data;
  37782. _this.isCompleted = true;
  37783. if (_this.onSuccess) {
  37784. _this.onSuccess(_this);
  37785. }
  37786. onSuccess();
  37787. }, null, scene.database, true, function () {
  37788. if (_this.onError) {
  37789. _this.onError(_this);
  37790. }
  37791. onError();
  37792. });
  37793. };
  37794. return BinaryFileAssetTask;
  37795. })();
  37796. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  37797. var ImageAssetTask = (function () {
  37798. function ImageAssetTask(name, url) {
  37799. this.name = name;
  37800. this.url = url;
  37801. this.isCompleted = false;
  37802. }
  37803. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37804. var _this = this;
  37805. var img = new Image();
  37806. img.onload = function () {
  37807. _this.image = img;
  37808. _this.isCompleted = true;
  37809. if (_this.onSuccess) {
  37810. _this.onSuccess(_this);
  37811. }
  37812. onSuccess();
  37813. };
  37814. img.onerror = function () {
  37815. if (_this.onError) {
  37816. _this.onError(_this);
  37817. }
  37818. onError();
  37819. };
  37820. img.src = this.url;
  37821. };
  37822. return ImageAssetTask;
  37823. })();
  37824. BABYLON.ImageAssetTask = ImageAssetTask;
  37825. var TextureAssetTask = (function () {
  37826. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  37827. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37828. this.name = name;
  37829. this.url = url;
  37830. this.noMipmap = noMipmap;
  37831. this.invertY = invertY;
  37832. this.samplingMode = samplingMode;
  37833. this.isCompleted = false;
  37834. }
  37835. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37836. var _this = this;
  37837. var onload = function () {
  37838. _this.isCompleted = true;
  37839. if (_this.onSuccess) {
  37840. _this.onSuccess(_this);
  37841. }
  37842. onSuccess();
  37843. };
  37844. var onerror = function () {
  37845. if (_this.onError) {
  37846. _this.onError(_this);
  37847. }
  37848. onError();
  37849. };
  37850. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  37851. };
  37852. return TextureAssetTask;
  37853. })();
  37854. BABYLON.TextureAssetTask = TextureAssetTask;
  37855. var AssetsManager = (function () {
  37856. function AssetsManager(scene) {
  37857. this._tasks = new Array();
  37858. this._waitingTasksCount = 0;
  37859. this.useDefaultLoadingScreen = true;
  37860. this._scene = scene;
  37861. }
  37862. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  37863. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  37864. this._tasks.push(task);
  37865. return task;
  37866. };
  37867. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  37868. var task = new TextFileAssetTask(taskName, url);
  37869. this._tasks.push(task);
  37870. return task;
  37871. };
  37872. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  37873. var task = new BinaryFileAssetTask(taskName, url);
  37874. this._tasks.push(task);
  37875. return task;
  37876. };
  37877. AssetsManager.prototype.addImageTask = function (taskName, url) {
  37878. var task = new ImageAssetTask(taskName, url);
  37879. this._tasks.push(task);
  37880. return task;
  37881. };
  37882. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  37883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37884. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  37885. this._tasks.push(task);
  37886. return task;
  37887. };
  37888. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  37889. this._waitingTasksCount--;
  37890. if (this._waitingTasksCount === 0) {
  37891. if (this.onFinish) {
  37892. this.onFinish(this._tasks);
  37893. }
  37894. this._scene.getEngine().hideLoadingUI();
  37895. }
  37896. };
  37897. AssetsManager.prototype._runTask = function (task) {
  37898. var _this = this;
  37899. task.run(this._scene, function () {
  37900. if (_this.onTaskSuccess) {
  37901. _this.onTaskSuccess(task);
  37902. }
  37903. _this._decreaseWaitingTasksCount();
  37904. }, function () {
  37905. if (_this.onTaskError) {
  37906. _this.onTaskError(task);
  37907. }
  37908. _this._decreaseWaitingTasksCount();
  37909. });
  37910. };
  37911. AssetsManager.prototype.reset = function () {
  37912. this._tasks = new Array();
  37913. return this;
  37914. };
  37915. AssetsManager.prototype.load = function () {
  37916. this._waitingTasksCount = this._tasks.length;
  37917. if (this._waitingTasksCount === 0) {
  37918. if (this.onFinish) {
  37919. this.onFinish(this._tasks);
  37920. }
  37921. return this;
  37922. }
  37923. if (this.useDefaultLoadingScreen) {
  37924. this._scene.getEngine().displayLoadingUI();
  37925. }
  37926. for (var index = 0; index < this._tasks.length; index++) {
  37927. var task = this._tasks[index];
  37928. this._runTask(task);
  37929. }
  37930. return this;
  37931. };
  37932. return AssetsManager;
  37933. })();
  37934. BABYLON.AssetsManager = AssetsManager;
  37935. })(BABYLON || (BABYLON = {}));
  37936. var BABYLON;
  37937. (function (BABYLON) {
  37938. var VRCameraMetrics = (function () {
  37939. function VRCameraMetrics() {
  37940. this.compensateDistortion = true;
  37941. }
  37942. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  37943. get: function () {
  37944. return this.hResolution / (2 * this.vResolution);
  37945. },
  37946. enumerable: true,
  37947. configurable: true
  37948. });
  37949. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  37950. get: function () {
  37951. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  37952. },
  37953. enumerable: true,
  37954. configurable: true
  37955. });
  37956. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  37957. get: function () {
  37958. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37959. var h = (4 * meters) / this.hScreenSize;
  37960. return BABYLON.Matrix.Translation(h, 0, 0);
  37961. },
  37962. enumerable: true,
  37963. configurable: true
  37964. });
  37965. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  37966. get: function () {
  37967. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37968. var h = (4 * meters) / this.hScreenSize;
  37969. return BABYLON.Matrix.Translation(-h, 0, 0);
  37970. },
  37971. enumerable: true,
  37972. configurable: true
  37973. });
  37974. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  37975. get: function () {
  37976. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  37977. },
  37978. enumerable: true,
  37979. configurable: true
  37980. });
  37981. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  37982. get: function () {
  37983. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  37984. },
  37985. enumerable: true,
  37986. configurable: true
  37987. });
  37988. VRCameraMetrics.GetDefault = function () {
  37989. var result = new VRCameraMetrics();
  37990. result.hResolution = 1280;
  37991. result.vResolution = 800;
  37992. result.hScreenSize = 0.149759993;
  37993. result.vScreenSize = 0.0935999975;
  37994. result.vScreenCenter = 0.0467999987,
  37995. result.eyeToScreenDistance = 0.0410000011;
  37996. result.lensSeparationDistance = 0.0635000020;
  37997. result.interpupillaryDistance = 0.0640000030;
  37998. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  37999. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  38000. result.postProcessScaleFactor = 1.714605507808412;
  38001. result.lensCenterOffset = 0.151976421;
  38002. return result;
  38003. };
  38004. return VRCameraMetrics;
  38005. })();
  38006. BABYLON.VRCameraMetrics = VRCameraMetrics;
  38007. })(BABYLON || (BABYLON = {}));
  38008. var BABYLON;
  38009. (function (BABYLON) {
  38010. var VRDeviceOrientationFreeCamera = (function (_super) {
  38011. __extends(VRDeviceOrientationFreeCamera, _super);
  38012. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  38013. if (compensateDistortion === void 0) { compensateDistortion = true; }
  38014. _super.call(this, name, position, scene);
  38015. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  38016. metrics.compensateDistortion = compensateDistortion;
  38017. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  38018. this.inputs.addVRDeviceOrientation();
  38019. }
  38020. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  38021. return "VRDeviceOrientationFreeCamera";
  38022. };
  38023. return VRDeviceOrientationFreeCamera;
  38024. })(BABYLON.FreeCamera);
  38025. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  38026. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  38027. __extends(VRDeviceOrientationArcRotateCamera, _super);
  38028. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  38029. if (compensateDistortion === void 0) { compensateDistortion = true; }
  38030. _super.call(this, name, alpha, beta, radius, target, scene);
  38031. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  38032. metrics.compensateDistortion = compensateDistortion;
  38033. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  38034. this.inputs.addVRDeviceOrientation();
  38035. }
  38036. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  38037. return "VRDeviceOrientationArcRotateCamera";
  38038. };
  38039. return VRDeviceOrientationArcRotateCamera;
  38040. })(BABYLON.ArcRotateCamera);
  38041. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  38042. })(BABYLON || (BABYLON = {}));
  38043. var BABYLON;
  38044. (function (BABYLON) {
  38045. var WebVRFreeCamera = (function (_super) {
  38046. __extends(WebVRFreeCamera, _super);
  38047. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  38048. if (compensateDistortion === void 0) { compensateDistortion = true; }
  38049. _super.call(this, name, position, scene);
  38050. this._hmdDevice = null;
  38051. this._sensorDevice = null;
  38052. this._cacheState = null;
  38053. this._cacheQuaternion = new BABYLON.Quaternion();
  38054. this._cacheRotation = BABYLON.Vector3.Zero();
  38055. this._vrEnabled = false;
  38056. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  38057. metrics.compensateDistortion = compensateDistortion;
  38058. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  38059. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  38060. }
  38061. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  38062. var size = devices.length;
  38063. var i = 0;
  38064. // Reset devices.
  38065. this._sensorDevice = null;
  38066. this._hmdDevice = null;
  38067. // Search for a HmdDevice.
  38068. while (i < size && this._hmdDevice === null) {
  38069. if (devices[i] instanceof HMDVRDevice) {
  38070. this._hmdDevice = devices[i];
  38071. }
  38072. i++;
  38073. }
  38074. i = 0;
  38075. while (i < size && this._sensorDevice === null) {
  38076. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  38077. this._sensorDevice = devices[i];
  38078. }
  38079. i++;
  38080. }
  38081. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  38082. };
  38083. WebVRFreeCamera.prototype._checkInputs = function () {
  38084. if (this._vrEnabled) {
  38085. this._cacheState = this._sensorDevice.getState();
  38086. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  38087. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  38088. this.rotation.x = -this._cacheRotation.x;
  38089. this.rotation.y = -this._cacheRotation.y;
  38090. this.rotation.z = this._cacheRotation.z;
  38091. }
  38092. _super.prototype._checkInputs.call(this);
  38093. };
  38094. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38095. _super.prototype.attachControl.call(this, element, noPreventDefault);
  38096. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38097. if (navigator.getVRDevices) {
  38098. navigator.getVRDevices().then(this._getWebVRDevices);
  38099. }
  38100. else if (navigator.mozGetVRDevices) {
  38101. navigator.mozGetVRDevices(this._getWebVRDevices);
  38102. }
  38103. };
  38104. WebVRFreeCamera.prototype.detachControl = function (element) {
  38105. _super.prototype.detachControl.call(this, element);
  38106. this._vrEnabled = false;
  38107. };
  38108. WebVRFreeCamera.prototype.getTypeName = function () {
  38109. return "WebVRFreeCamera";
  38110. };
  38111. return WebVRFreeCamera;
  38112. })(BABYLON.FreeCamera);
  38113. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  38114. })(BABYLON || (BABYLON = {}));
  38115. var BABYLON;
  38116. (function (BABYLON) {
  38117. // Standard optimizations
  38118. var SceneOptimization = (function () {
  38119. function SceneOptimization(priority) {
  38120. if (priority === void 0) { priority = 0; }
  38121. this.priority = priority;
  38122. this.apply = function (scene) {
  38123. return true; // Return true if everything that can be done was applied
  38124. };
  38125. }
  38126. return SceneOptimization;
  38127. })();
  38128. BABYLON.SceneOptimization = SceneOptimization;
  38129. var TextureOptimization = (function (_super) {
  38130. __extends(TextureOptimization, _super);
  38131. function TextureOptimization(priority, maximumSize) {
  38132. var _this = this;
  38133. if (priority === void 0) { priority = 0; }
  38134. if (maximumSize === void 0) { maximumSize = 1024; }
  38135. _super.call(this, priority);
  38136. this.priority = priority;
  38137. this.maximumSize = maximumSize;
  38138. this.apply = function (scene) {
  38139. var allDone = true;
  38140. for (var index = 0; index < scene.textures.length; index++) {
  38141. var texture = scene.textures[index];
  38142. if (!texture.canRescale) {
  38143. continue;
  38144. }
  38145. var currentSize = texture.getSize();
  38146. var maxDimension = Math.max(currentSize.width, currentSize.height);
  38147. if (maxDimension > _this.maximumSize) {
  38148. texture.scale(0.5);
  38149. allDone = false;
  38150. }
  38151. }
  38152. return allDone;
  38153. };
  38154. }
  38155. return TextureOptimization;
  38156. })(SceneOptimization);
  38157. BABYLON.TextureOptimization = TextureOptimization;
  38158. var HardwareScalingOptimization = (function (_super) {
  38159. __extends(HardwareScalingOptimization, _super);
  38160. function HardwareScalingOptimization(priority, maximumScale) {
  38161. var _this = this;
  38162. if (priority === void 0) { priority = 0; }
  38163. if (maximumScale === void 0) { maximumScale = 2; }
  38164. _super.call(this, priority);
  38165. this.priority = priority;
  38166. this.maximumScale = maximumScale;
  38167. this._currentScale = 1;
  38168. this.apply = function (scene) {
  38169. _this._currentScale++;
  38170. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  38171. return _this._currentScale >= _this.maximumScale;
  38172. };
  38173. }
  38174. return HardwareScalingOptimization;
  38175. })(SceneOptimization);
  38176. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  38177. var ShadowsOptimization = (function (_super) {
  38178. __extends(ShadowsOptimization, _super);
  38179. function ShadowsOptimization() {
  38180. _super.apply(this, arguments);
  38181. this.apply = function (scene) {
  38182. scene.shadowsEnabled = false;
  38183. return true;
  38184. };
  38185. }
  38186. return ShadowsOptimization;
  38187. })(SceneOptimization);
  38188. BABYLON.ShadowsOptimization = ShadowsOptimization;
  38189. var PostProcessesOptimization = (function (_super) {
  38190. __extends(PostProcessesOptimization, _super);
  38191. function PostProcessesOptimization() {
  38192. _super.apply(this, arguments);
  38193. this.apply = function (scene) {
  38194. scene.postProcessesEnabled = false;
  38195. return true;
  38196. };
  38197. }
  38198. return PostProcessesOptimization;
  38199. })(SceneOptimization);
  38200. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  38201. var LensFlaresOptimization = (function (_super) {
  38202. __extends(LensFlaresOptimization, _super);
  38203. function LensFlaresOptimization() {
  38204. _super.apply(this, arguments);
  38205. this.apply = function (scene) {
  38206. scene.lensFlaresEnabled = false;
  38207. return true;
  38208. };
  38209. }
  38210. return LensFlaresOptimization;
  38211. })(SceneOptimization);
  38212. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  38213. var ParticlesOptimization = (function (_super) {
  38214. __extends(ParticlesOptimization, _super);
  38215. function ParticlesOptimization() {
  38216. _super.apply(this, arguments);
  38217. this.apply = function (scene) {
  38218. scene.particlesEnabled = false;
  38219. return true;
  38220. };
  38221. }
  38222. return ParticlesOptimization;
  38223. })(SceneOptimization);
  38224. BABYLON.ParticlesOptimization = ParticlesOptimization;
  38225. var RenderTargetsOptimization = (function (_super) {
  38226. __extends(RenderTargetsOptimization, _super);
  38227. function RenderTargetsOptimization() {
  38228. _super.apply(this, arguments);
  38229. this.apply = function (scene) {
  38230. scene.renderTargetsEnabled = false;
  38231. return true;
  38232. };
  38233. }
  38234. return RenderTargetsOptimization;
  38235. })(SceneOptimization);
  38236. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  38237. var MergeMeshesOptimization = (function (_super) {
  38238. __extends(MergeMeshesOptimization, _super);
  38239. function MergeMeshesOptimization() {
  38240. var _this = this;
  38241. _super.apply(this, arguments);
  38242. this._canBeMerged = function (abstractMesh) {
  38243. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  38244. return false;
  38245. }
  38246. var mesh = abstractMesh;
  38247. if (!mesh.isVisible || !mesh.isEnabled()) {
  38248. return false;
  38249. }
  38250. if (mesh.instances.length > 0) {
  38251. return false;
  38252. }
  38253. if (mesh.skeleton || mesh.hasLODLevels) {
  38254. return false;
  38255. }
  38256. if (mesh.parent) {
  38257. return false;
  38258. }
  38259. return true;
  38260. };
  38261. this.apply = function (scene, updateSelectionTree) {
  38262. var globalPool = scene.meshes.slice(0);
  38263. var globalLength = globalPool.length;
  38264. for (var index = 0; index < globalLength; index++) {
  38265. var currentPool = new Array();
  38266. var current = globalPool[index];
  38267. // Checks
  38268. if (!_this._canBeMerged(current)) {
  38269. continue;
  38270. }
  38271. currentPool.push(current);
  38272. // Find compatible meshes
  38273. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  38274. var otherMesh = globalPool[subIndex];
  38275. if (!_this._canBeMerged(otherMesh)) {
  38276. continue;
  38277. }
  38278. if (otherMesh.material !== current.material) {
  38279. continue;
  38280. }
  38281. if (otherMesh.checkCollisions !== current.checkCollisions) {
  38282. continue;
  38283. }
  38284. currentPool.push(otherMesh);
  38285. globalLength--;
  38286. globalPool.splice(subIndex, 1);
  38287. subIndex--;
  38288. }
  38289. if (currentPool.length < 2) {
  38290. continue;
  38291. }
  38292. // Merge meshes
  38293. BABYLON.Mesh.MergeMeshes(currentPool);
  38294. }
  38295. if (updateSelectionTree != undefined) {
  38296. if (updateSelectionTree) {
  38297. scene.createOrUpdateSelectionOctree();
  38298. }
  38299. }
  38300. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  38301. scene.createOrUpdateSelectionOctree();
  38302. }
  38303. return true;
  38304. };
  38305. }
  38306. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  38307. get: function () {
  38308. return MergeMeshesOptimization._UpdateSelectionTree;
  38309. },
  38310. set: function (value) {
  38311. MergeMeshesOptimization._UpdateSelectionTree = value;
  38312. },
  38313. enumerable: true,
  38314. configurable: true
  38315. });
  38316. MergeMeshesOptimization._UpdateSelectionTree = false;
  38317. return MergeMeshesOptimization;
  38318. })(SceneOptimization);
  38319. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  38320. // Options
  38321. var SceneOptimizerOptions = (function () {
  38322. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  38323. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  38324. if (trackerDuration === void 0) { trackerDuration = 2000; }
  38325. this.targetFrameRate = targetFrameRate;
  38326. this.trackerDuration = trackerDuration;
  38327. this.optimizations = new Array();
  38328. }
  38329. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  38330. var result = new SceneOptimizerOptions(targetFrameRate);
  38331. var priority = 0;
  38332. result.optimizations.push(new MergeMeshesOptimization(priority));
  38333. result.optimizations.push(new ShadowsOptimization(priority));
  38334. result.optimizations.push(new LensFlaresOptimization(priority));
  38335. // Next priority
  38336. priority++;
  38337. result.optimizations.push(new PostProcessesOptimization(priority));
  38338. result.optimizations.push(new ParticlesOptimization(priority));
  38339. // Next priority
  38340. priority++;
  38341. result.optimizations.push(new TextureOptimization(priority, 1024));
  38342. return result;
  38343. };
  38344. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  38345. var result = new SceneOptimizerOptions(targetFrameRate);
  38346. var priority = 0;
  38347. result.optimizations.push(new MergeMeshesOptimization(priority));
  38348. result.optimizations.push(new ShadowsOptimization(priority));
  38349. result.optimizations.push(new LensFlaresOptimization(priority));
  38350. // Next priority
  38351. priority++;
  38352. result.optimizations.push(new PostProcessesOptimization(priority));
  38353. result.optimizations.push(new ParticlesOptimization(priority));
  38354. // Next priority
  38355. priority++;
  38356. result.optimizations.push(new TextureOptimization(priority, 512));
  38357. // Next priority
  38358. priority++;
  38359. result.optimizations.push(new RenderTargetsOptimization(priority));
  38360. // Next priority
  38361. priority++;
  38362. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  38363. return result;
  38364. };
  38365. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  38366. var result = new SceneOptimizerOptions(targetFrameRate);
  38367. var priority = 0;
  38368. result.optimizations.push(new MergeMeshesOptimization(priority));
  38369. result.optimizations.push(new ShadowsOptimization(priority));
  38370. result.optimizations.push(new LensFlaresOptimization(priority));
  38371. // Next priority
  38372. priority++;
  38373. result.optimizations.push(new PostProcessesOptimization(priority));
  38374. result.optimizations.push(new ParticlesOptimization(priority));
  38375. // Next priority
  38376. priority++;
  38377. result.optimizations.push(new TextureOptimization(priority, 256));
  38378. // Next priority
  38379. priority++;
  38380. result.optimizations.push(new RenderTargetsOptimization(priority));
  38381. // Next priority
  38382. priority++;
  38383. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  38384. return result;
  38385. };
  38386. return SceneOptimizerOptions;
  38387. })();
  38388. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  38389. // Scene optimizer tool
  38390. var SceneOptimizer = (function () {
  38391. function SceneOptimizer() {
  38392. }
  38393. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  38394. // TODO: add an epsilon
  38395. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  38396. if (onSuccess) {
  38397. onSuccess();
  38398. }
  38399. return;
  38400. }
  38401. // Apply current level of optimizations
  38402. var allDone = true;
  38403. var noOptimizationApplied = true;
  38404. for (var index = 0; index < options.optimizations.length; index++) {
  38405. var optimization = options.optimizations[index];
  38406. if (optimization.priority === currentPriorityLevel) {
  38407. noOptimizationApplied = false;
  38408. allDone = allDone && optimization.apply(scene);
  38409. }
  38410. }
  38411. // If no optimization was applied, this is a failure :(
  38412. if (noOptimizationApplied) {
  38413. if (onFailure) {
  38414. onFailure();
  38415. }
  38416. return;
  38417. }
  38418. // If all optimizations were done, move to next level
  38419. if (allDone) {
  38420. currentPriorityLevel++;
  38421. }
  38422. // Let's the system running for a specific amount of time before checking FPS
  38423. scene.executeWhenReady(function () {
  38424. setTimeout(function () {
  38425. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  38426. }, options.trackerDuration);
  38427. });
  38428. };
  38429. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  38430. if (!options) {
  38431. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  38432. }
  38433. // Let's the system running for a specific amount of time before checking FPS
  38434. scene.executeWhenReady(function () {
  38435. setTimeout(function () {
  38436. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  38437. }, options.trackerDuration);
  38438. });
  38439. };
  38440. return SceneOptimizer;
  38441. })();
  38442. BABYLON.SceneOptimizer = SceneOptimizer;
  38443. })(BABYLON || (BABYLON = {}));
  38444. var BABYLON;
  38445. (function (BABYLON) {
  38446. var Internals;
  38447. (function (Internals) {
  38448. var MeshLODLevel = (function () {
  38449. function MeshLODLevel(distance, mesh) {
  38450. this.distance = distance;
  38451. this.mesh = mesh;
  38452. }
  38453. return MeshLODLevel;
  38454. })();
  38455. Internals.MeshLODLevel = MeshLODLevel;
  38456. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38457. })(BABYLON || (BABYLON = {}));
  38458. var BABYLON;
  38459. (function (BABYLON) {
  38460. var RawTexture = (function (_super) {
  38461. __extends(RawTexture, _super);
  38462. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  38463. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38464. if (invertY === void 0) { invertY = false; }
  38465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38466. _super.call(this, null, scene, !generateMipMaps, invertY);
  38467. this.format = format;
  38468. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  38469. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38470. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38471. }
  38472. RawTexture.prototype.update = function (data) {
  38473. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  38474. };
  38475. // Statics
  38476. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38477. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38478. if (invertY === void 0) { invertY = false; }
  38479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38480. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  38481. };
  38482. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38483. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38484. if (invertY === void 0) { invertY = false; }
  38485. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38486. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  38487. };
  38488. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38489. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38490. if (invertY === void 0) { invertY = false; }
  38491. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38492. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  38493. };
  38494. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38495. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38496. if (invertY === void 0) { invertY = false; }
  38497. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38498. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  38499. };
  38500. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38501. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38502. if (invertY === void 0) { invertY = false; }
  38503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38504. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  38505. };
  38506. return RawTexture;
  38507. })(BABYLON.Texture);
  38508. BABYLON.RawTexture = RawTexture;
  38509. })(BABYLON || (BABYLON = {}));
  38510. var BABYLON;
  38511. (function (BABYLON) {
  38512. var IndexedVector2 = (function (_super) {
  38513. __extends(IndexedVector2, _super);
  38514. function IndexedVector2(original, index) {
  38515. _super.call(this, original.x, original.y);
  38516. this.index = index;
  38517. }
  38518. return IndexedVector2;
  38519. })(BABYLON.Vector2);
  38520. var PolygonPoints = (function () {
  38521. function PolygonPoints() {
  38522. this.elements = new Array();
  38523. }
  38524. PolygonPoints.prototype.add = function (originalPoints) {
  38525. var _this = this;
  38526. var result = new Array();
  38527. originalPoints.forEach(function (point) {
  38528. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  38529. var newPoint = new IndexedVector2(point, _this.elements.length);
  38530. result.push(newPoint);
  38531. _this.elements.push(newPoint);
  38532. }
  38533. });
  38534. return result;
  38535. };
  38536. PolygonPoints.prototype.computeBounds = function () {
  38537. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  38538. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  38539. this.elements.forEach(function (point) {
  38540. // x
  38541. if (point.x < lmin.x) {
  38542. lmin.x = point.x;
  38543. }
  38544. else if (point.x > lmax.x) {
  38545. lmax.x = point.x;
  38546. }
  38547. // y
  38548. if (point.y < lmin.y) {
  38549. lmin.y = point.y;
  38550. }
  38551. else if (point.y > lmax.y) {
  38552. lmax.y = point.y;
  38553. }
  38554. });
  38555. return {
  38556. min: lmin,
  38557. max: lmax,
  38558. width: lmax.x - lmin.x,
  38559. height: lmax.y - lmin.y
  38560. };
  38561. };
  38562. return PolygonPoints;
  38563. })();
  38564. var Polygon = (function () {
  38565. function Polygon() {
  38566. }
  38567. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  38568. return [
  38569. new BABYLON.Vector2(xmin, ymin),
  38570. new BABYLON.Vector2(xmax, ymin),
  38571. new BABYLON.Vector2(xmax, ymax),
  38572. new BABYLON.Vector2(xmin, ymax)
  38573. ];
  38574. };
  38575. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  38576. if (cx === void 0) { cx = 0; }
  38577. if (cy === void 0) { cy = 0; }
  38578. if (numberOfSides === void 0) { numberOfSides = 32; }
  38579. var result = new Array();
  38580. var angle = 0;
  38581. var increment = (Math.PI * 2) / numberOfSides;
  38582. for (var i = 0; i < numberOfSides; i++) {
  38583. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  38584. angle -= increment;
  38585. }
  38586. return result;
  38587. };
  38588. Polygon.Parse = function (input) {
  38589. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  38590. var i, result = [];
  38591. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  38592. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  38593. }
  38594. return result;
  38595. };
  38596. Polygon.StartingAt = function (x, y) {
  38597. return BABYLON.Path2.StartingAt(x, y);
  38598. };
  38599. return Polygon;
  38600. })();
  38601. BABYLON.Polygon = Polygon;
  38602. var PolygonMeshBuilder = (function () {
  38603. function PolygonMeshBuilder(name, contours, scene) {
  38604. this._points = new PolygonPoints();
  38605. this._outlinepoints = new PolygonPoints();
  38606. this._holes = [];
  38607. if (!("poly2tri" in window)) {
  38608. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  38609. }
  38610. this._name = name;
  38611. this._scene = scene;
  38612. var points;
  38613. if (contours instanceof BABYLON.Path2) {
  38614. points = contours.getPoints();
  38615. }
  38616. else {
  38617. points = contours;
  38618. }
  38619. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  38620. this._outlinepoints.add(points);
  38621. }
  38622. PolygonMeshBuilder.prototype.addHole = function (hole) {
  38623. this._swctx.addHole(this._points.add(hole));
  38624. var holepoints = new PolygonPoints();
  38625. holepoints.add(hole);
  38626. this._holes.push(holepoints);
  38627. return this;
  38628. };
  38629. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  38630. var _this = this;
  38631. if (updatable === void 0) { updatable = false; }
  38632. var result = new BABYLON.Mesh(this._name, this._scene);
  38633. var normals = [];
  38634. var positions = [];
  38635. var uvs = [];
  38636. var bounds = this._points.computeBounds();
  38637. this._points.elements.forEach(function (p) {
  38638. normals.push(0, 1.0, 0);
  38639. positions.push(p.x, 0, p.y);
  38640. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  38641. });
  38642. var indices = [];
  38643. this._swctx.triangulate();
  38644. this._swctx.getTriangles().forEach(function (triangle) {
  38645. triangle.getPoints().forEach(function (point) {
  38646. indices.push(point.index);
  38647. });
  38648. });
  38649. if (depth > 0) {
  38650. var positionscount = (positions.length / 3); //get the current pointcount
  38651. this._points.elements.forEach(function (p) {
  38652. normals.push(0, -1.0, 0);
  38653. positions.push(p.x, -depth, p.y);
  38654. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  38655. });
  38656. var p1; //we need to change order of point so the triangles are made in the rigth way.
  38657. var p2;
  38658. var poscounter = 0;
  38659. this._swctx.getTriangles().forEach(function (triangle) {
  38660. triangle.getPoints().forEach(function (point) {
  38661. switch (poscounter) {
  38662. case 0:
  38663. p1 = point;
  38664. break;
  38665. case 1:
  38666. p2 = point;
  38667. break;
  38668. case 2:
  38669. indices.push(point.index + positionscount);
  38670. indices.push(p2.index + positionscount);
  38671. indices.push(p1.index + positionscount);
  38672. poscounter = -1;
  38673. break;
  38674. }
  38675. poscounter++;
  38676. //indices.push((<IndexedVector2>point).index + positionscount);
  38677. });
  38678. });
  38679. //Add the sides
  38680. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  38681. this._holes.forEach(function (hole) {
  38682. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  38683. });
  38684. }
  38685. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  38686. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  38687. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  38688. result.setIndices(indices);
  38689. return result;
  38690. };
  38691. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  38692. var StartIndex = positions.length / 3;
  38693. var ulength = 0;
  38694. for (var i = 0; i < points.elements.length; i++) {
  38695. var p = points.elements[i];
  38696. var p1;
  38697. if ((i + 1) > points.elements.length - 1) {
  38698. p1 = points.elements[0];
  38699. }
  38700. else {
  38701. p1 = points.elements[i + 1];
  38702. }
  38703. positions.push(p.x, 0, p.y);
  38704. positions.push(p.x, -depth, p.y);
  38705. positions.push(p1.x, 0, p1.y);
  38706. positions.push(p1.x, -depth, p1.y);
  38707. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  38708. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  38709. var v3 = v2.subtract(v1);
  38710. var v4 = new BABYLON.Vector3(0, 1, 0);
  38711. var vn = BABYLON.Vector3.Cross(v3, v4);
  38712. vn = vn.normalize();
  38713. uvs.push(ulength / bounds.width, 0);
  38714. uvs.push(ulength / bounds.width, 1);
  38715. ulength += v3.length();
  38716. uvs.push((ulength / bounds.width), 0);
  38717. uvs.push((ulength / bounds.width), 1);
  38718. if (!flip) {
  38719. normals.push(-vn.x, -vn.y, -vn.z);
  38720. normals.push(-vn.x, -vn.y, -vn.z);
  38721. normals.push(-vn.x, -vn.y, -vn.z);
  38722. normals.push(-vn.x, -vn.y, -vn.z);
  38723. indices.push(StartIndex);
  38724. indices.push(StartIndex + 1);
  38725. indices.push(StartIndex + 2);
  38726. indices.push(StartIndex + 1);
  38727. indices.push(StartIndex + 3);
  38728. indices.push(StartIndex + 2);
  38729. }
  38730. else {
  38731. normals.push(vn.x, vn.y, vn.z);
  38732. normals.push(vn.x, vn.y, vn.z);
  38733. normals.push(vn.x, vn.y, vn.z);
  38734. normals.push(vn.x, vn.y, vn.z);
  38735. indices.push(StartIndex);
  38736. indices.push(StartIndex + 2);
  38737. indices.push(StartIndex + 1);
  38738. indices.push(StartIndex + 1);
  38739. indices.push(StartIndex + 2);
  38740. indices.push(StartIndex + 3);
  38741. }
  38742. StartIndex += 4;
  38743. }
  38744. ;
  38745. };
  38746. return PolygonMeshBuilder;
  38747. })();
  38748. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  38749. })(BABYLON || (BABYLON = {}));
  38750. var BABYLON;
  38751. (function (BABYLON) {
  38752. var Octree = (function () {
  38753. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  38754. if (maxDepth === void 0) { maxDepth = 2; }
  38755. this.maxDepth = maxDepth;
  38756. this.dynamicContent = new Array();
  38757. this._maxBlockCapacity = maxBlockCapacity || 64;
  38758. this._selectionContent = new BABYLON.SmartArray(1024);
  38759. this._creationFunc = creationFunc;
  38760. }
  38761. // Methods
  38762. Octree.prototype.update = function (worldMin, worldMax, entries) {
  38763. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  38764. };
  38765. Octree.prototype.addMesh = function (entry) {
  38766. for (var index = 0; index < this.blocks.length; index++) {
  38767. var block = this.blocks[index];
  38768. block.addEntry(entry);
  38769. }
  38770. };
  38771. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  38772. this._selectionContent.reset();
  38773. for (var index = 0; index < this.blocks.length; index++) {
  38774. var block = this.blocks[index];
  38775. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  38776. }
  38777. if (allowDuplicate) {
  38778. this._selectionContent.concat(this.dynamicContent);
  38779. }
  38780. else {
  38781. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38782. }
  38783. return this._selectionContent;
  38784. };
  38785. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  38786. this._selectionContent.reset();
  38787. for (var index = 0; index < this.blocks.length; index++) {
  38788. var block = this.blocks[index];
  38789. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  38790. }
  38791. if (allowDuplicate) {
  38792. this._selectionContent.concat(this.dynamicContent);
  38793. }
  38794. else {
  38795. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38796. }
  38797. return this._selectionContent;
  38798. };
  38799. Octree.prototype.intersectsRay = function (ray) {
  38800. this._selectionContent.reset();
  38801. for (var index = 0; index < this.blocks.length; index++) {
  38802. var block = this.blocks[index];
  38803. block.intersectsRay(ray, this._selectionContent);
  38804. }
  38805. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38806. return this._selectionContent;
  38807. };
  38808. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  38809. target.blocks = new Array();
  38810. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  38811. // Segmenting space
  38812. for (var x = 0; x < 2; x++) {
  38813. for (var y = 0; y < 2; y++) {
  38814. for (var z = 0; z < 2; z++) {
  38815. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  38816. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  38817. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  38818. block.addEntries(entries);
  38819. target.blocks.push(block);
  38820. }
  38821. }
  38822. }
  38823. };
  38824. Octree.CreationFuncForMeshes = function (entry, block) {
  38825. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38826. block.entries.push(entry);
  38827. }
  38828. };
  38829. Octree.CreationFuncForSubMeshes = function (entry, block) {
  38830. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38831. block.entries.push(entry);
  38832. }
  38833. };
  38834. return Octree;
  38835. })();
  38836. BABYLON.Octree = Octree;
  38837. })(BABYLON || (BABYLON = {}));
  38838. var BABYLON;
  38839. (function (BABYLON) {
  38840. var OctreeBlock = (function () {
  38841. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  38842. this.entries = new Array();
  38843. this._boundingVectors = new Array();
  38844. this._capacity = capacity;
  38845. this._depth = depth;
  38846. this._maxDepth = maxDepth;
  38847. this._creationFunc = creationFunc;
  38848. this._minPoint = minPoint;
  38849. this._maxPoint = maxPoint;
  38850. this._boundingVectors.push(minPoint.clone());
  38851. this._boundingVectors.push(maxPoint.clone());
  38852. this._boundingVectors.push(minPoint.clone());
  38853. this._boundingVectors[2].x = maxPoint.x;
  38854. this._boundingVectors.push(minPoint.clone());
  38855. this._boundingVectors[3].y = maxPoint.y;
  38856. this._boundingVectors.push(minPoint.clone());
  38857. this._boundingVectors[4].z = maxPoint.z;
  38858. this._boundingVectors.push(maxPoint.clone());
  38859. this._boundingVectors[5].z = minPoint.z;
  38860. this._boundingVectors.push(maxPoint.clone());
  38861. this._boundingVectors[6].x = minPoint.x;
  38862. this._boundingVectors.push(maxPoint.clone());
  38863. this._boundingVectors[7].y = minPoint.y;
  38864. }
  38865. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  38866. // Property
  38867. get: function () {
  38868. return this._capacity;
  38869. },
  38870. enumerable: true,
  38871. configurable: true
  38872. });
  38873. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  38874. get: function () {
  38875. return this._minPoint;
  38876. },
  38877. enumerable: true,
  38878. configurable: true
  38879. });
  38880. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  38881. get: function () {
  38882. return this._maxPoint;
  38883. },
  38884. enumerable: true,
  38885. configurable: true
  38886. });
  38887. // Methods
  38888. OctreeBlock.prototype.addEntry = function (entry) {
  38889. if (this.blocks) {
  38890. for (var index = 0; index < this.blocks.length; index++) {
  38891. var block = this.blocks[index];
  38892. block.addEntry(entry);
  38893. }
  38894. return;
  38895. }
  38896. this._creationFunc(entry, this);
  38897. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  38898. this.createInnerBlocks();
  38899. }
  38900. };
  38901. OctreeBlock.prototype.addEntries = function (entries) {
  38902. for (var index = 0; index < entries.length; index++) {
  38903. var mesh = entries[index];
  38904. this.addEntry(mesh);
  38905. }
  38906. };
  38907. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  38908. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  38909. if (this.blocks) {
  38910. for (var index = 0; index < this.blocks.length; index++) {
  38911. var block = this.blocks[index];
  38912. block.select(frustumPlanes, selection, allowDuplicate);
  38913. }
  38914. return;
  38915. }
  38916. if (allowDuplicate) {
  38917. selection.concat(this.entries);
  38918. }
  38919. else {
  38920. selection.concatWithNoDuplicate(this.entries);
  38921. }
  38922. }
  38923. };
  38924. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  38925. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  38926. if (this.blocks) {
  38927. for (var index = 0; index < this.blocks.length; index++) {
  38928. var block = this.blocks[index];
  38929. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  38930. }
  38931. return;
  38932. }
  38933. if (allowDuplicate) {
  38934. selection.concat(this.entries);
  38935. }
  38936. else {
  38937. selection.concatWithNoDuplicate(this.entries);
  38938. }
  38939. }
  38940. };
  38941. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  38942. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  38943. if (this.blocks) {
  38944. for (var index = 0; index < this.blocks.length; index++) {
  38945. var block = this.blocks[index];
  38946. block.intersectsRay(ray, selection);
  38947. }
  38948. return;
  38949. }
  38950. selection.concatWithNoDuplicate(this.entries);
  38951. }
  38952. };
  38953. OctreeBlock.prototype.createInnerBlocks = function () {
  38954. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  38955. };
  38956. return OctreeBlock;
  38957. })();
  38958. BABYLON.OctreeBlock = OctreeBlock;
  38959. })(BABYLON || (BABYLON = {}));
  38960. var BABYLON;
  38961. (function (BABYLON) {
  38962. var BlurPostProcess = (function (_super) {
  38963. __extends(BlurPostProcess, _super);
  38964. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  38965. var _this = this;
  38966. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38967. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  38968. this.direction = direction;
  38969. this.blurWidth = blurWidth;
  38970. this.onApply = function (effect) {
  38971. effect.setFloat2("screenSize", _this.width, _this.height);
  38972. effect.setVector2("direction", _this.direction);
  38973. effect.setFloat("blurWidth", _this.blurWidth);
  38974. };
  38975. }
  38976. return BlurPostProcess;
  38977. })(BABYLON.PostProcess);
  38978. BABYLON.BlurPostProcess = BlurPostProcess;
  38979. })(BABYLON || (BABYLON = {}));
  38980. var BABYLON;
  38981. (function (BABYLON) {
  38982. var RefractionPostProcess = (function (_super) {
  38983. __extends(RefractionPostProcess, _super);
  38984. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  38985. var _this = this;
  38986. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  38987. this.color = color;
  38988. this.depth = depth;
  38989. this.colorLevel = colorLevel;
  38990. this.onActivate = function (cam) {
  38991. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  38992. };
  38993. this.onApply = function (effect) {
  38994. effect.setColor3("baseColor", _this.color);
  38995. effect.setFloat("depth", _this.depth);
  38996. effect.setFloat("colorLevel", _this.colorLevel);
  38997. effect.setTexture("refractionSampler", _this._refRexture);
  38998. };
  38999. }
  39000. // Methods
  39001. RefractionPostProcess.prototype.dispose = function (camera) {
  39002. if (this._refRexture) {
  39003. this._refRexture.dispose();
  39004. }
  39005. _super.prototype.dispose.call(this, camera);
  39006. };
  39007. return RefractionPostProcess;
  39008. })(BABYLON.PostProcess);
  39009. BABYLON.RefractionPostProcess = RefractionPostProcess;
  39010. })(BABYLON || (BABYLON = {}));
  39011. var BABYLON;
  39012. (function (BABYLON) {
  39013. var BlackAndWhitePostProcess = (function (_super) {
  39014. __extends(BlackAndWhitePostProcess, _super);
  39015. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  39016. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  39017. }
  39018. return BlackAndWhitePostProcess;
  39019. })(BABYLON.PostProcess);
  39020. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  39021. })(BABYLON || (BABYLON = {}));
  39022. var BABYLON;
  39023. (function (BABYLON) {
  39024. var ConvolutionPostProcess = (function (_super) {
  39025. __extends(ConvolutionPostProcess, _super);
  39026. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  39027. var _this = this;
  39028. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  39029. this.kernel = kernel;
  39030. this.onApply = function (effect) {
  39031. effect.setFloat2("screenSize", _this.width, _this.height);
  39032. effect.setArray("kernel", _this.kernel);
  39033. };
  39034. }
  39035. // Statics
  39036. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  39037. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  39038. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  39039. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  39040. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  39041. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  39042. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  39043. return ConvolutionPostProcess;
  39044. })(BABYLON.PostProcess);
  39045. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  39046. })(BABYLON || (BABYLON = {}));
  39047. var BABYLON;
  39048. (function (BABYLON) {
  39049. var FilterPostProcess = (function (_super) {
  39050. __extends(FilterPostProcess, _super);
  39051. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  39052. var _this = this;
  39053. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  39054. this.kernelMatrix = kernelMatrix;
  39055. this.onApply = function (effect) {
  39056. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  39057. };
  39058. }
  39059. return FilterPostProcess;
  39060. })(BABYLON.PostProcess);
  39061. BABYLON.FilterPostProcess = FilterPostProcess;
  39062. })(BABYLON || (BABYLON = {}));
  39063. var BABYLON;
  39064. (function (BABYLON) {
  39065. var FxaaPostProcess = (function (_super) {
  39066. __extends(FxaaPostProcess, _super);
  39067. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  39068. var _this = this;
  39069. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  39070. this.onSizeChanged = function () {
  39071. _this.texelWidth = 1.0 / _this.width;
  39072. _this.texelHeight = 1.0 / _this.height;
  39073. };
  39074. this.onApply = function (effect) {
  39075. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  39076. };
  39077. }
  39078. return FxaaPostProcess;
  39079. })(BABYLON.PostProcess);
  39080. BABYLON.FxaaPostProcess = FxaaPostProcess;
  39081. })(BABYLON || (BABYLON = {}));
  39082. var BABYLON;
  39083. (function (BABYLON) {
  39084. var StereoscopicInterlacePostProcess = (function (_super) {
  39085. __extends(StereoscopicInterlacePostProcess, _super);
  39086. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  39087. var _this = this;
  39088. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  39089. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  39090. this.onSizeChanged = function () {
  39091. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  39092. };
  39093. this.onApply = function (effect) {
  39094. effect.setTextureFromPostProcess("camASampler", postProcessA);
  39095. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  39096. };
  39097. }
  39098. return StereoscopicInterlacePostProcess;
  39099. })(BABYLON.PostProcess);
  39100. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  39101. })(BABYLON || (BABYLON = {}));
  39102. var BABYLON;
  39103. (function (BABYLON) {
  39104. var LensFlare = (function () {
  39105. function LensFlare(size, position, color, imgUrl, system) {
  39106. this.size = size;
  39107. this.position = position;
  39108. this.dispose = function () {
  39109. if (this.texture) {
  39110. this.texture.dispose();
  39111. }
  39112. // Remove from scene
  39113. var index = this._system.lensFlares.indexOf(this);
  39114. this._system.lensFlares.splice(index, 1);
  39115. };
  39116. this.color = color || new BABYLON.Color3(1, 1, 1);
  39117. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  39118. this._system = system;
  39119. system.lensFlares.push(this);
  39120. }
  39121. return LensFlare;
  39122. })();
  39123. BABYLON.LensFlare = LensFlare;
  39124. })(BABYLON || (BABYLON = {}));
  39125. var BABYLON;
  39126. (function (BABYLON) {
  39127. var LensFlareSystem = (function () {
  39128. function LensFlareSystem(name, emitter, scene) {
  39129. this.name = name;
  39130. this.lensFlares = new Array();
  39131. this.borderLimit = 300;
  39132. this.layerMask = 0x0FFFFFFF;
  39133. this._vertexDeclaration = [2];
  39134. this._vertexStrideSize = 2 * 4;
  39135. this._isEnabled = true;
  39136. this._scene = scene;
  39137. this._emitter = emitter;
  39138. this.id = name;
  39139. scene.lensFlareSystems.push(this);
  39140. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  39141. // VBO
  39142. var vertices = [];
  39143. vertices.push(1, 1);
  39144. vertices.push(-1, 1);
  39145. vertices.push(-1, -1);
  39146. vertices.push(1, -1);
  39147. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  39148. // Indices
  39149. var indices = [];
  39150. indices.push(0);
  39151. indices.push(1);
  39152. indices.push(2);
  39153. indices.push(0);
  39154. indices.push(2);
  39155. indices.push(3);
  39156. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39157. // Effects
  39158. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  39159. }
  39160. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  39161. get: function () {
  39162. return this._isEnabled;
  39163. },
  39164. set: function (value) {
  39165. this._isEnabled = value;
  39166. },
  39167. enumerable: true,
  39168. configurable: true
  39169. });
  39170. LensFlareSystem.prototype.getScene = function () {
  39171. return this._scene;
  39172. };
  39173. LensFlareSystem.prototype.getEmitter = function () {
  39174. return this._emitter;
  39175. };
  39176. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  39177. this._emitter = newEmitter;
  39178. };
  39179. LensFlareSystem.prototype.getEmitterPosition = function () {
  39180. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  39181. };
  39182. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  39183. var position = this.getEmitterPosition();
  39184. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  39185. this._positionX = position.x;
  39186. this._positionY = position.y;
  39187. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  39188. if (position.z > 0) {
  39189. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  39190. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  39191. return true;
  39192. }
  39193. }
  39194. return false;
  39195. };
  39196. LensFlareSystem.prototype._isVisible = function () {
  39197. if (!this._isEnabled) {
  39198. return false;
  39199. }
  39200. var emitterPosition = this.getEmitterPosition();
  39201. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  39202. var distance = direction.length();
  39203. direction.normalize();
  39204. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  39205. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  39206. return !pickInfo.hit || pickInfo.distance > distance;
  39207. };
  39208. LensFlareSystem.prototype.render = function () {
  39209. if (!this._effect.isReady())
  39210. return false;
  39211. var engine = this._scene.getEngine();
  39212. var viewport = this._scene.activeCamera.viewport;
  39213. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  39214. // Position
  39215. if (!this.computeEffectivePosition(globalViewport)) {
  39216. return false;
  39217. }
  39218. // Visibility
  39219. if (!this._isVisible()) {
  39220. return false;
  39221. }
  39222. // Intensity
  39223. var awayX;
  39224. var awayY;
  39225. if (this._positionX < this.borderLimit + globalViewport.x) {
  39226. awayX = this.borderLimit + globalViewport.x - this._positionX;
  39227. }
  39228. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  39229. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  39230. }
  39231. else {
  39232. awayX = 0;
  39233. }
  39234. if (this._positionY < this.borderLimit + globalViewport.y) {
  39235. awayY = this.borderLimit + globalViewport.y - this._positionY;
  39236. }
  39237. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  39238. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  39239. }
  39240. else {
  39241. awayY = 0;
  39242. }
  39243. var away = (awayX > awayY) ? awayX : awayY;
  39244. if (away > this.borderLimit) {
  39245. away = this.borderLimit;
  39246. }
  39247. var intensity = 1.0 - (away / this.borderLimit);
  39248. if (intensity < 0) {
  39249. return false;
  39250. }
  39251. if (intensity > 1.0) {
  39252. intensity = 1.0;
  39253. }
  39254. // Position
  39255. var centerX = globalViewport.x + globalViewport.width / 2;
  39256. var centerY = globalViewport.y + globalViewport.height / 2;
  39257. var distX = centerX - this._positionX;
  39258. var distY = centerY - this._positionY;
  39259. // Effects
  39260. engine.enableEffect(this._effect);
  39261. engine.setState(false);
  39262. engine.setDepthBuffer(false);
  39263. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  39264. // VBOs
  39265. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  39266. // Flares
  39267. for (var index = 0; index < this.lensFlares.length; index++) {
  39268. var flare = this.lensFlares[index];
  39269. var x = centerX - (distX * flare.position);
  39270. var y = centerY - (distY * flare.position);
  39271. var cw = flare.size;
  39272. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  39273. var cx = 2 * (x / globalViewport.width) - 1.0;
  39274. var cy = 1.0 - 2 * (y / globalViewport.height);
  39275. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  39276. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  39277. // Texture
  39278. this._effect.setTexture("textureSampler", flare.texture);
  39279. // Color
  39280. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  39281. // Draw order
  39282. engine.draw(true, 0, 6);
  39283. }
  39284. engine.setDepthBuffer(true);
  39285. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39286. return true;
  39287. };
  39288. LensFlareSystem.prototype.dispose = function () {
  39289. if (this._vertexBuffer) {
  39290. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  39291. this._vertexBuffer = null;
  39292. }
  39293. if (this._indexBuffer) {
  39294. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39295. this._indexBuffer = null;
  39296. }
  39297. while (this.lensFlares.length) {
  39298. this.lensFlares[0].dispose();
  39299. }
  39300. // Remove from scene
  39301. var index = this._scene.lensFlareSystems.indexOf(this);
  39302. this._scene.lensFlareSystems.splice(index, 1);
  39303. };
  39304. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  39305. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  39306. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  39307. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  39308. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  39309. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  39310. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  39311. var parsedFlare = parsedLensFlareSystem.flares[index];
  39312. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  39313. }
  39314. return lensFlareSystem;
  39315. };
  39316. LensFlareSystem.prototype.serialize = function () {
  39317. var serializationObject = {};
  39318. serializationObject.id = this.id;
  39319. serializationObject.name = this.name;
  39320. serializationObject.emitterId = this.getEmitter().id;
  39321. serializationObject.borderLimit = this.borderLimit;
  39322. serializationObject.flares = [];
  39323. for (var index = 0; index < this.lensFlares.length; index++) {
  39324. var flare = this.lensFlares[index];
  39325. serializationObject.flares.push({
  39326. size: flare.size,
  39327. position: flare.position,
  39328. color: flare.color.asArray(),
  39329. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  39330. });
  39331. }
  39332. return serializationObject;
  39333. };
  39334. return LensFlareSystem;
  39335. })();
  39336. BABYLON.LensFlareSystem = LensFlareSystem;
  39337. })(BABYLON || (BABYLON = {}));
  39338. var BABYLON;
  39339. (function (BABYLON) {
  39340. // We're mainly based on the logic defined into the FreeCamera code
  39341. var DeviceOrientationCamera = (function (_super) {
  39342. __extends(DeviceOrientationCamera, _super);
  39343. //-- end properties for backward compatibility for inputs
  39344. function DeviceOrientationCamera(name, position, scene) {
  39345. _super.call(this, name, position, scene);
  39346. this.inputs.addDeviceOrientation();
  39347. }
  39348. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  39349. //-- Begin properties for backward compatibility for inputs
  39350. get: function () {
  39351. var gamepad = this.inputs.attached["deviceOrientation"];
  39352. if (gamepad)
  39353. return gamepad.angularSensibility;
  39354. },
  39355. set: function (value) {
  39356. var gamepad = this.inputs.attached["deviceOrientation"];
  39357. if (gamepad)
  39358. gamepad.angularSensibility = value;
  39359. },
  39360. enumerable: true,
  39361. configurable: true
  39362. });
  39363. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  39364. get: function () {
  39365. var gamepad = this.inputs.attached["deviceOrientation"];
  39366. if (gamepad)
  39367. return gamepad.moveSensibility;
  39368. },
  39369. set: function (value) {
  39370. var gamepad = this.inputs.attached["deviceOrientation"];
  39371. if (gamepad)
  39372. gamepad.moveSensibility = value;
  39373. },
  39374. enumerable: true,
  39375. configurable: true
  39376. });
  39377. DeviceOrientationCamera.prototype.getTypeName = function () {
  39378. return "DeviceOrientationCamera";
  39379. };
  39380. return DeviceOrientationCamera;
  39381. })(BABYLON.FreeCamera);
  39382. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  39383. })(BABYLON || (BABYLON = {}));
  39384. var BABYLON;
  39385. (function (BABYLON) {
  39386. // We're mainly based on the logic defined into the FreeCamera code
  39387. var UniversalCamera = (function (_super) {
  39388. __extends(UniversalCamera, _super);
  39389. //-- end properties for backward compatibility for inputs
  39390. function UniversalCamera(name, position, scene) {
  39391. _super.call(this, name, position, scene);
  39392. this.inputs.addGamepad();
  39393. }
  39394. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  39395. //-- Begin properties for backward compatibility for inputs
  39396. get: function () {
  39397. var gamepad = this.inputs.attached["gamepad"];
  39398. if (gamepad)
  39399. return gamepad.gamepadAngularSensibility;
  39400. },
  39401. set: function (value) {
  39402. var gamepad = this.inputs.attached["gamepad"];
  39403. if (gamepad)
  39404. gamepad.gamepadAngularSensibility = value;
  39405. },
  39406. enumerable: true,
  39407. configurable: true
  39408. });
  39409. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  39410. get: function () {
  39411. var gamepad = this.inputs.attached["gamepad"];
  39412. if (gamepad)
  39413. return gamepad.gamepadMoveSensibility;
  39414. },
  39415. set: function (value) {
  39416. var gamepad = this.inputs.attached["gamepad"];
  39417. if (gamepad)
  39418. gamepad.gamepadMoveSensibility = value;
  39419. },
  39420. enumerable: true,
  39421. configurable: true
  39422. });
  39423. UniversalCamera.prototype.getTypeName = function () {
  39424. return "UniversalCamera";
  39425. };
  39426. return UniversalCamera;
  39427. })(BABYLON.TouchCamera);
  39428. BABYLON.UniversalCamera = UniversalCamera;
  39429. })(BABYLON || (BABYLON = {}));
  39430. var BABYLON;
  39431. (function (BABYLON) {
  39432. var Gamepads = (function () {
  39433. function Gamepads(ongamedpadconnected) {
  39434. var _this = this;
  39435. this.babylonGamepads = [];
  39436. this.oneGamepadConnected = false;
  39437. this.isMonitoring = false;
  39438. this.gamepadEventSupported = 'GamepadEvent' in window;
  39439. this.gamepadSupportAvailable = (navigator.getGamepads ||
  39440. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  39441. this._callbackGamepadConnected = ongamedpadconnected;
  39442. if (this.gamepadSupportAvailable) {
  39443. // Checking if the gamepad connected event is supported (like in Firefox)
  39444. if (this.gamepadEventSupported) {
  39445. this._onGamepadConnectedEvent = function (evt) {
  39446. _this._onGamepadConnected(evt);
  39447. };
  39448. this._onGamepadDisonnectedEvent = function (evt) {
  39449. _this._onGamepadDisconnected(evt);
  39450. };
  39451. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  39452. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  39453. }
  39454. else {
  39455. this._startMonitoringGamepads();
  39456. }
  39457. }
  39458. }
  39459. Gamepads.prototype.dispose = function () {
  39460. if (Gamepads.gamepadDOMInfo) {
  39461. document.body.removeChild(Gamepads.gamepadDOMInfo);
  39462. }
  39463. if (this._onGamepadConnectedEvent) {
  39464. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  39465. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  39466. this._onGamepadConnectedEvent = null;
  39467. this._onGamepadDisonnectedEvent = null;
  39468. }
  39469. };
  39470. Gamepads.prototype._onGamepadConnected = function (evt) {
  39471. var newGamepad = this._addNewGamepad(evt.gamepad);
  39472. if (this._callbackGamepadConnected)
  39473. this._callbackGamepadConnected(newGamepad);
  39474. this._startMonitoringGamepads();
  39475. };
  39476. Gamepads.prototype._addNewGamepad = function (gamepad) {
  39477. if (!this.oneGamepadConnected) {
  39478. this.oneGamepadConnected = true;
  39479. if (Gamepads.gamepadDOMInfo) {
  39480. document.body.removeChild(Gamepads.gamepadDOMInfo);
  39481. Gamepads.gamepadDOMInfo = null;
  39482. }
  39483. }
  39484. var newGamepad;
  39485. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  39486. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  39487. }
  39488. else {
  39489. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  39490. }
  39491. this.babylonGamepads.push(newGamepad);
  39492. return newGamepad;
  39493. };
  39494. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  39495. // Remove the gamepad from the list of gamepads to monitor.
  39496. for (var i in this.babylonGamepads) {
  39497. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  39498. this.babylonGamepads.splice(+i, 1);
  39499. break;
  39500. }
  39501. }
  39502. // If no gamepads are left, stop the polling loop.
  39503. if (this.babylonGamepads.length == 0) {
  39504. this._stopMonitoringGamepads();
  39505. }
  39506. };
  39507. Gamepads.prototype._startMonitoringGamepads = function () {
  39508. if (!this.isMonitoring) {
  39509. this.isMonitoring = true;
  39510. this._checkGamepadsStatus();
  39511. }
  39512. };
  39513. Gamepads.prototype._stopMonitoringGamepads = function () {
  39514. this.isMonitoring = false;
  39515. };
  39516. Gamepads.prototype._checkGamepadsStatus = function () {
  39517. var _this = this;
  39518. // updating gamepad objects
  39519. this._updateGamepadObjects();
  39520. for (var i in this.babylonGamepads) {
  39521. this.babylonGamepads[i].update();
  39522. }
  39523. if (this.isMonitoring) {
  39524. if (window.requestAnimationFrame) {
  39525. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39526. }
  39527. else if (window.mozRequestAnimationFrame) {
  39528. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39529. }
  39530. else if (window.webkitRequestAnimationFrame) {
  39531. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39532. }
  39533. }
  39534. };
  39535. // This function is called only on Chrome, which does not yet support
  39536. // connection/disconnection events, but requires you to monitor
  39537. // an array for changes.
  39538. Gamepads.prototype._updateGamepadObjects = function () {
  39539. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  39540. for (var i = 0; i < gamepads.length; i++) {
  39541. if (gamepads[i]) {
  39542. if (!(gamepads[i].index in this.babylonGamepads)) {
  39543. var newGamepad = this._addNewGamepad(gamepads[i]);
  39544. if (this._callbackGamepadConnected) {
  39545. this._callbackGamepadConnected(newGamepad);
  39546. }
  39547. }
  39548. else {
  39549. this.babylonGamepads[i].browserGamepad = gamepads[i];
  39550. }
  39551. }
  39552. }
  39553. };
  39554. return Gamepads;
  39555. })();
  39556. BABYLON.Gamepads = Gamepads;
  39557. var StickValues = (function () {
  39558. function StickValues(x, y) {
  39559. this.x = x;
  39560. this.y = y;
  39561. }
  39562. return StickValues;
  39563. })();
  39564. BABYLON.StickValues = StickValues;
  39565. var Gamepad = (function () {
  39566. function Gamepad(id, index, browserGamepad) {
  39567. this.id = id;
  39568. this.index = index;
  39569. this.browserGamepad = browserGamepad;
  39570. if (this.browserGamepad.axes.length >= 2) {
  39571. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39572. }
  39573. if (this.browserGamepad.axes.length >= 4) {
  39574. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39575. }
  39576. }
  39577. Gamepad.prototype.onleftstickchanged = function (callback) {
  39578. this._onleftstickchanged = callback;
  39579. };
  39580. Gamepad.prototype.onrightstickchanged = function (callback) {
  39581. this._onrightstickchanged = callback;
  39582. };
  39583. Object.defineProperty(Gamepad.prototype, "leftStick", {
  39584. get: function () {
  39585. return this._leftStick;
  39586. },
  39587. set: function (newValues) {
  39588. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  39589. this._onleftstickchanged(newValues);
  39590. }
  39591. this._leftStick = newValues;
  39592. },
  39593. enumerable: true,
  39594. configurable: true
  39595. });
  39596. Object.defineProperty(Gamepad.prototype, "rightStick", {
  39597. get: function () {
  39598. return this._rightStick;
  39599. },
  39600. set: function (newValues) {
  39601. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  39602. this._onrightstickchanged(newValues);
  39603. }
  39604. this._rightStick = newValues;
  39605. },
  39606. enumerable: true,
  39607. configurable: true
  39608. });
  39609. Gamepad.prototype.update = function () {
  39610. if (this._leftStick) {
  39611. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39612. }
  39613. if (this._rightStick) {
  39614. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39615. }
  39616. };
  39617. return Gamepad;
  39618. })();
  39619. BABYLON.Gamepad = Gamepad;
  39620. var GenericPad = (function (_super) {
  39621. __extends(GenericPad, _super);
  39622. function GenericPad(id, index, gamepad) {
  39623. _super.call(this, id, index, gamepad);
  39624. this.id = id;
  39625. this.index = index;
  39626. this.gamepad = gamepad;
  39627. this._buttons = new Array(gamepad.buttons.length);
  39628. }
  39629. GenericPad.prototype.onbuttondown = function (callback) {
  39630. this._onbuttondown = callback;
  39631. };
  39632. GenericPad.prototype.onbuttonup = function (callback) {
  39633. this._onbuttonup = callback;
  39634. };
  39635. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  39636. if (newValue !== currentValue) {
  39637. if (this._onbuttondown && newValue === 1) {
  39638. this._onbuttondown(buttonIndex);
  39639. }
  39640. if (this._onbuttonup && newValue === 0) {
  39641. this._onbuttonup(buttonIndex);
  39642. }
  39643. }
  39644. return newValue;
  39645. };
  39646. GenericPad.prototype.update = function () {
  39647. _super.prototype.update.call(this);
  39648. for (var index = 0; index < this._buttons.length; index++) {
  39649. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  39650. }
  39651. };
  39652. return GenericPad;
  39653. })(Gamepad);
  39654. BABYLON.GenericPad = GenericPad;
  39655. (function (Xbox360Button) {
  39656. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  39657. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  39658. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  39659. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  39660. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  39661. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  39662. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  39663. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  39664. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  39665. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  39666. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  39667. var Xbox360Button = BABYLON.Xbox360Button;
  39668. (function (Xbox360Dpad) {
  39669. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  39670. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  39671. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  39672. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  39673. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  39674. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  39675. var Xbox360Pad = (function (_super) {
  39676. __extends(Xbox360Pad, _super);
  39677. function Xbox360Pad() {
  39678. _super.apply(this, arguments);
  39679. this._leftTrigger = 0;
  39680. this._rightTrigger = 0;
  39681. this._buttonA = 0;
  39682. this._buttonB = 0;
  39683. this._buttonX = 0;
  39684. this._buttonY = 0;
  39685. this._buttonBack = 0;
  39686. this._buttonStart = 0;
  39687. this._buttonLB = 0;
  39688. this._buttonRB = 0;
  39689. this._buttonLeftStick = 0;
  39690. this._buttonRightStick = 0;
  39691. this._dPadUp = 0;
  39692. this._dPadDown = 0;
  39693. this._dPadLeft = 0;
  39694. this._dPadRight = 0;
  39695. }
  39696. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  39697. this._onlefttriggerchanged = callback;
  39698. };
  39699. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  39700. this._onrighttriggerchanged = callback;
  39701. };
  39702. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  39703. get: function () {
  39704. return this._leftTrigger;
  39705. },
  39706. set: function (newValue) {
  39707. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  39708. this._onlefttriggerchanged(newValue);
  39709. }
  39710. this._leftTrigger = newValue;
  39711. },
  39712. enumerable: true,
  39713. configurable: true
  39714. });
  39715. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  39716. get: function () {
  39717. return this._rightTrigger;
  39718. },
  39719. set: function (newValue) {
  39720. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  39721. this._onrighttriggerchanged(newValue);
  39722. }
  39723. this._rightTrigger = newValue;
  39724. },
  39725. enumerable: true,
  39726. configurable: true
  39727. });
  39728. Xbox360Pad.prototype.onbuttondown = function (callback) {
  39729. this._onbuttondown = callback;
  39730. };
  39731. Xbox360Pad.prototype.onbuttonup = function (callback) {
  39732. this._onbuttonup = callback;
  39733. };
  39734. Xbox360Pad.prototype.ondpaddown = function (callback) {
  39735. this._ondpaddown = callback;
  39736. };
  39737. Xbox360Pad.prototype.ondpadup = function (callback) {
  39738. this._ondpadup = callback;
  39739. };
  39740. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  39741. if (newValue !== currentValue) {
  39742. if (this._onbuttondown && newValue === 1) {
  39743. this._onbuttondown(buttonType);
  39744. }
  39745. if (this._onbuttonup && newValue === 0) {
  39746. this._onbuttonup(buttonType);
  39747. }
  39748. }
  39749. return newValue;
  39750. };
  39751. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  39752. if (newValue !== currentValue) {
  39753. if (this._ondpaddown && newValue === 1) {
  39754. this._ondpaddown(buttonType);
  39755. }
  39756. if (this._ondpadup && newValue === 0) {
  39757. this._ondpadup(buttonType);
  39758. }
  39759. }
  39760. return newValue;
  39761. };
  39762. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  39763. get: function () {
  39764. return this._buttonA;
  39765. },
  39766. set: function (value) {
  39767. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  39768. },
  39769. enumerable: true,
  39770. configurable: true
  39771. });
  39772. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  39773. get: function () {
  39774. return this._buttonB;
  39775. },
  39776. set: function (value) {
  39777. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  39778. },
  39779. enumerable: true,
  39780. configurable: true
  39781. });
  39782. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  39783. get: function () {
  39784. return this._buttonX;
  39785. },
  39786. set: function (value) {
  39787. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  39788. },
  39789. enumerable: true,
  39790. configurable: true
  39791. });
  39792. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  39793. get: function () {
  39794. return this._buttonY;
  39795. },
  39796. set: function (value) {
  39797. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  39798. },
  39799. enumerable: true,
  39800. configurable: true
  39801. });
  39802. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  39803. get: function () {
  39804. return this._buttonStart;
  39805. },
  39806. set: function (value) {
  39807. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  39808. },
  39809. enumerable: true,
  39810. configurable: true
  39811. });
  39812. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  39813. get: function () {
  39814. return this._buttonBack;
  39815. },
  39816. set: function (value) {
  39817. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  39818. },
  39819. enumerable: true,
  39820. configurable: true
  39821. });
  39822. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  39823. get: function () {
  39824. return this._buttonLB;
  39825. },
  39826. set: function (value) {
  39827. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  39828. },
  39829. enumerable: true,
  39830. configurable: true
  39831. });
  39832. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  39833. get: function () {
  39834. return this._buttonRB;
  39835. },
  39836. set: function (value) {
  39837. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  39838. },
  39839. enumerable: true,
  39840. configurable: true
  39841. });
  39842. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  39843. get: function () {
  39844. return this._buttonLeftStick;
  39845. },
  39846. set: function (value) {
  39847. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  39848. },
  39849. enumerable: true,
  39850. configurable: true
  39851. });
  39852. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  39853. get: function () {
  39854. return this._buttonRightStick;
  39855. },
  39856. set: function (value) {
  39857. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  39858. },
  39859. enumerable: true,
  39860. configurable: true
  39861. });
  39862. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  39863. get: function () {
  39864. return this._dPadUp;
  39865. },
  39866. set: function (value) {
  39867. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  39868. },
  39869. enumerable: true,
  39870. configurable: true
  39871. });
  39872. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  39873. get: function () {
  39874. return this._dPadDown;
  39875. },
  39876. set: function (value) {
  39877. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  39878. },
  39879. enumerable: true,
  39880. configurable: true
  39881. });
  39882. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  39883. get: function () {
  39884. return this._dPadLeft;
  39885. },
  39886. set: function (value) {
  39887. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  39888. },
  39889. enumerable: true,
  39890. configurable: true
  39891. });
  39892. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  39893. get: function () {
  39894. return this._dPadRight;
  39895. },
  39896. set: function (value) {
  39897. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  39898. },
  39899. enumerable: true,
  39900. configurable: true
  39901. });
  39902. Xbox360Pad.prototype.update = function () {
  39903. _super.prototype.update.call(this);
  39904. this.buttonA = this.browserGamepad.buttons[0].value;
  39905. this.buttonB = this.browserGamepad.buttons[1].value;
  39906. this.buttonX = this.browserGamepad.buttons[2].value;
  39907. this.buttonY = this.browserGamepad.buttons[3].value;
  39908. this.buttonLB = this.browserGamepad.buttons[4].value;
  39909. this.buttonRB = this.browserGamepad.buttons[5].value;
  39910. this.leftTrigger = this.browserGamepad.buttons[6].value;
  39911. this.rightTrigger = this.browserGamepad.buttons[7].value;
  39912. this.buttonBack = this.browserGamepad.buttons[8].value;
  39913. this.buttonStart = this.browserGamepad.buttons[9].value;
  39914. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  39915. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  39916. this.dPadUp = this.browserGamepad.buttons[12].value;
  39917. this.dPadDown = this.browserGamepad.buttons[13].value;
  39918. this.dPadLeft = this.browserGamepad.buttons[14].value;
  39919. this.dPadRight = this.browserGamepad.buttons[15].value;
  39920. };
  39921. return Xbox360Pad;
  39922. })(Gamepad);
  39923. BABYLON.Xbox360Pad = Xbox360Pad;
  39924. })(BABYLON || (BABYLON = {}));
  39925. var BABYLON;
  39926. (function (BABYLON) {
  39927. // We're mainly based on the logic defined into the FreeCamera code
  39928. var GamepadCamera = (function (_super) {
  39929. __extends(GamepadCamera, _super);
  39930. //-- end properties for backward compatibility for inputs
  39931. function GamepadCamera(name, position, scene) {
  39932. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  39933. _super.call(this, name, position, scene);
  39934. }
  39935. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  39936. //-- Begin properties for backward compatibility for inputs
  39937. get: function () {
  39938. var gamepad = this.inputs.attached["gamepad"];
  39939. if (gamepad)
  39940. return gamepad.gamepadAngularSensibility;
  39941. },
  39942. set: function (value) {
  39943. var gamepad = this.inputs.attached["gamepad"];
  39944. if (gamepad)
  39945. gamepad.gamepadAngularSensibility = value;
  39946. },
  39947. enumerable: true,
  39948. configurable: true
  39949. });
  39950. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  39951. get: function () {
  39952. var gamepad = this.inputs.attached["gamepad"];
  39953. if (gamepad)
  39954. return gamepad.gamepadMoveSensibility;
  39955. },
  39956. set: function (value) {
  39957. var gamepad = this.inputs.attached["gamepad"];
  39958. if (gamepad)
  39959. gamepad.gamepadMoveSensibility = value;
  39960. },
  39961. enumerable: true,
  39962. configurable: true
  39963. });
  39964. GamepadCamera.prototype.getTypeName = function () {
  39965. return "GamepadCamera";
  39966. };
  39967. return GamepadCamera;
  39968. })(BABYLON.UniversalCamera);
  39969. BABYLON.GamepadCamera = GamepadCamera;
  39970. })(BABYLON || (BABYLON = {}));
  39971. var BABYLON;
  39972. (function (BABYLON) {
  39973. var Analyser = (function () {
  39974. function Analyser(scene) {
  39975. this.SMOOTHING = 0.75;
  39976. this.FFT_SIZE = 512;
  39977. this.BARGRAPHAMPLITUDE = 256;
  39978. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  39979. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  39980. this._scene = scene;
  39981. this._audioEngine = BABYLON.Engine.audioEngine;
  39982. if (this._audioEngine.canUseWebAudio) {
  39983. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  39984. this._webAudioAnalyser.minDecibels = -140;
  39985. this._webAudioAnalyser.maxDecibels = 0;
  39986. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39987. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39988. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  39989. }
  39990. }
  39991. Analyser.prototype.getFrequencyBinCount = function () {
  39992. if (this._audioEngine.canUseWebAudio) {
  39993. return this._webAudioAnalyser.frequencyBinCount;
  39994. }
  39995. else {
  39996. return 0;
  39997. }
  39998. };
  39999. Analyser.prototype.getByteFrequencyData = function () {
  40000. if (this._audioEngine.canUseWebAudio) {
  40001. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40002. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40003. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  40004. }
  40005. return this._byteFreqs;
  40006. };
  40007. Analyser.prototype.getByteTimeDomainData = function () {
  40008. if (this._audioEngine.canUseWebAudio) {
  40009. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40010. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40011. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  40012. }
  40013. return this._byteTime;
  40014. };
  40015. Analyser.prototype.getFloatFrequencyData = function () {
  40016. if (this._audioEngine.canUseWebAudio) {
  40017. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40018. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40019. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  40020. }
  40021. return this._floatFreqs;
  40022. };
  40023. Analyser.prototype.drawDebugCanvas = function () {
  40024. var _this = this;
  40025. if (this._audioEngine.canUseWebAudio) {
  40026. if (!this._debugCanvas) {
  40027. this._debugCanvas = document.createElement("canvas");
  40028. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  40029. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  40030. this._debugCanvas.style.position = "absolute";
  40031. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  40032. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  40033. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  40034. document.body.appendChild(this._debugCanvas);
  40035. this._registerFunc = function () {
  40036. _this.drawDebugCanvas();
  40037. };
  40038. this._scene.registerBeforeRender(this._registerFunc);
  40039. }
  40040. if (this._registerFunc) {
  40041. var workingArray = this.getByteFrequencyData();
  40042. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  40043. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  40044. // Draw the frequency domain chart.
  40045. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  40046. var value = workingArray[i];
  40047. var percent = value / this.BARGRAPHAMPLITUDE;
  40048. var height = this.DEBUGCANVASSIZE.height * percent;
  40049. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  40050. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  40051. var hue = i / this.getFrequencyBinCount() * 360;
  40052. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  40053. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  40054. }
  40055. }
  40056. }
  40057. };
  40058. Analyser.prototype.stopDebugCanvas = function () {
  40059. if (this._debugCanvas) {
  40060. this._scene.unregisterBeforeRender(this._registerFunc);
  40061. this._registerFunc = null;
  40062. document.body.removeChild(this._debugCanvas);
  40063. this._debugCanvas = null;
  40064. this._debugCanvasContext = null;
  40065. }
  40066. };
  40067. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  40068. if (this._audioEngine.canUseWebAudio) {
  40069. inputAudioNode.connect(this._webAudioAnalyser);
  40070. this._webAudioAnalyser.connect(outputAudioNode);
  40071. }
  40072. };
  40073. Analyser.prototype.dispose = function () {
  40074. if (this._audioEngine.canUseWebAudio) {
  40075. this._webAudioAnalyser.disconnect();
  40076. }
  40077. };
  40078. return Analyser;
  40079. })();
  40080. BABYLON.Analyser = Analyser;
  40081. })(BABYLON || (BABYLON = {}));
  40082. var BABYLON;
  40083. (function (BABYLON) {
  40084. var DepthRenderer = (function () {
  40085. function DepthRenderer(scene, type) {
  40086. var _this = this;
  40087. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  40088. this._viewMatrix = BABYLON.Matrix.Zero();
  40089. this._projectionMatrix = BABYLON.Matrix.Zero();
  40090. this._transformMatrix = BABYLON.Matrix.Zero();
  40091. this._worldViewProjection = BABYLON.Matrix.Zero();
  40092. this._scene = scene;
  40093. var engine = scene.getEngine();
  40094. // Render target
  40095. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  40096. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40097. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40098. this._depthMap.refreshRate = 1;
  40099. this._depthMap.renderParticles = false;
  40100. this._depthMap.renderList = null;
  40101. // set default depth value to 1.0 (far away)
  40102. this._depthMap.onClear = function (engine) {
  40103. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  40104. };
  40105. // Custom render function
  40106. var renderSubMesh = function (subMesh) {
  40107. var mesh = subMesh.getRenderingMesh();
  40108. var scene = _this._scene;
  40109. var engine = scene.getEngine();
  40110. // Culling
  40111. engine.setState(subMesh.getMaterial().backFaceCulling);
  40112. // Managing instances
  40113. var batch = mesh._getInstancesRenderList(subMesh._id);
  40114. if (batch.mustReturn) {
  40115. return;
  40116. }
  40117. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  40118. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40119. engine.enableEffect(_this._effect);
  40120. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  40121. var material = subMesh.getMaterial();
  40122. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  40123. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  40124. // Alpha test
  40125. if (material && material.needAlphaTesting()) {
  40126. var alphaTexture = material.getAlphaTestTexture();
  40127. _this._effect.setTexture("diffuseSampler", alphaTexture);
  40128. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40129. }
  40130. // Bones
  40131. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40132. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40133. }
  40134. // Draw
  40135. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  40136. }
  40137. };
  40138. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  40139. var index;
  40140. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40141. renderSubMesh(opaqueSubMeshes.data[index]);
  40142. }
  40143. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40144. renderSubMesh(alphaTestSubMeshes.data[index]);
  40145. }
  40146. };
  40147. }
  40148. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  40149. var material = subMesh.getMaterial();
  40150. if (material.disableDepthWrite) {
  40151. return false;
  40152. }
  40153. var defines = [];
  40154. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40155. var mesh = subMesh.getMesh();
  40156. var scene = mesh.getScene();
  40157. // Alpha test
  40158. if (material && material.needAlphaTesting()) {
  40159. defines.push("#define ALPHATEST");
  40160. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40161. attribs.push(BABYLON.VertexBuffer.UVKind);
  40162. defines.push("#define UV1");
  40163. }
  40164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40165. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40166. defines.push("#define UV2");
  40167. }
  40168. }
  40169. // Bones
  40170. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40171. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40172. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40173. if (mesh.numBoneInfluencers > 4) {
  40174. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40175. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40176. }
  40177. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40178. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40179. }
  40180. else {
  40181. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40182. }
  40183. // Instances
  40184. if (useInstances) {
  40185. defines.push("#define INSTANCES");
  40186. attribs.push("world0");
  40187. attribs.push("world1");
  40188. attribs.push("world2");
  40189. attribs.push("world3");
  40190. }
  40191. // Get correct effect
  40192. var join = defines.join("\n");
  40193. if (this._cachedDefines !== join) {
  40194. this._cachedDefines = join;
  40195. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  40196. }
  40197. return this._effect.isReady();
  40198. };
  40199. DepthRenderer.prototype.getDepthMap = function () {
  40200. return this._depthMap;
  40201. };
  40202. // Methods
  40203. DepthRenderer.prototype.dispose = function () {
  40204. this._depthMap.dispose();
  40205. };
  40206. return DepthRenderer;
  40207. })();
  40208. BABYLON.DepthRenderer = DepthRenderer;
  40209. })(BABYLON || (BABYLON = {}));
  40210. var BABYLON;
  40211. (function (BABYLON) {
  40212. var SSAORenderingPipeline = (function (_super) {
  40213. __extends(SSAORenderingPipeline, _super);
  40214. /**
  40215. * @constructor
  40216. * @param {string} name - The rendering pipeline name
  40217. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40218. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  40219. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40220. */
  40221. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  40222. var _this = this;
  40223. _super.call(this, scene.getEngine(), name);
  40224. // Members
  40225. /**
  40226. * The PassPostProcess id in the pipeline that contains the original scene color
  40227. * @type {string}
  40228. */
  40229. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  40230. /**
  40231. * The SSAO PostProcess id in the pipeline
  40232. * @type {string}
  40233. */
  40234. this.SSAORenderEffect = "SSAORenderEffect";
  40235. /**
  40236. * The horizontal blur PostProcess id in the pipeline
  40237. * @type {string}
  40238. */
  40239. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  40240. /**
  40241. * The vertical blur PostProcess id in the pipeline
  40242. * @type {string}
  40243. */
  40244. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  40245. /**
  40246. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  40247. * @type {string}
  40248. */
  40249. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  40250. /**
  40251. * The output strength of the SSAO post-process. Default value is 1.0.
  40252. * @type {number}
  40253. */
  40254. this.totalStrength = 1.0;
  40255. /**
  40256. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  40257. * @type {number}
  40258. */
  40259. this.radius = 0.0001;
  40260. /**
  40261. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  40262. * Must not be equal to fallOff and superior to fallOff.
  40263. * Default value is 0.975
  40264. * @type {number}
  40265. */
  40266. this.area = 0.0075;
  40267. /**
  40268. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  40269. * Must not be equal to area and inferior to area.
  40270. * Default value is 0.0
  40271. * @type {number}
  40272. */
  40273. this.fallOff = 0.000001;
  40274. /**
  40275. * The base color of the SSAO post-process
  40276. * The final result is "base + ssao" between [0, 1]
  40277. * @type {number}
  40278. */
  40279. this.base = 0.5;
  40280. this._firstUpdate = true;
  40281. this._scene = scene;
  40282. // Set up assets
  40283. this._createRandomTexture();
  40284. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  40285. var ssaoRatio = ratio.ssaoRatio || ratio;
  40286. var combineRatio = ratio.combineRatio || ratio;
  40287. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40288. this._createSSAOPostProcess(ssaoRatio);
  40289. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40290. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40291. this._createSSAOCombinePostProcess(combineRatio);
  40292. // Set up pipeline
  40293. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  40294. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  40295. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  40296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  40297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  40298. // Finish
  40299. scene.postProcessRenderPipelineManager.addPipeline(this);
  40300. if (cameras)
  40301. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40302. }
  40303. // Public Methods
  40304. /**
  40305. * Returns the horizontal blur PostProcess
  40306. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  40307. */
  40308. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  40309. return this._blurHPostProcess;
  40310. };
  40311. /**
  40312. * Returns the vertical blur PostProcess
  40313. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  40314. */
  40315. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  40316. return this._blurVPostProcess;
  40317. };
  40318. /**
  40319. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  40320. */
  40321. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  40322. if (disableDepthRender === void 0) { disableDepthRender = false; }
  40323. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40324. this._originalColorPostProcess = undefined;
  40325. this._ssaoPostProcess = undefined;
  40326. this._blurHPostProcess = undefined;
  40327. this._blurVPostProcess = undefined;
  40328. this._ssaoCombinePostProcess = undefined;
  40329. this._randomTexture.dispose();
  40330. if (disableDepthRender)
  40331. this._scene.disableDepthRenderer();
  40332. };
  40333. // Private Methods
  40334. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  40335. var _this = this;
  40336. var numSamples = 16;
  40337. var sampleSphere = [
  40338. 0.5381, 0.1856, -0.4319,
  40339. 0.1379, 0.2486, 0.4430,
  40340. 0.3371, 0.5679, -0.0057,
  40341. -0.6999, -0.0451, -0.0019,
  40342. 0.0689, -0.1598, -0.8547,
  40343. 0.0560, 0.0069, -0.1843,
  40344. -0.0146, 0.1402, 0.0762,
  40345. 0.0100, -0.1924, -0.0344,
  40346. -0.3577, -0.5301, -0.4358,
  40347. -0.3169, 0.1063, 0.0158,
  40348. 0.0103, -0.5869, 0.0046,
  40349. -0.0897, -0.4940, 0.3287,
  40350. 0.7119, -0.0154, -0.0918,
  40351. -0.0533, 0.0596, -0.5411,
  40352. 0.0352, -0.0631, 0.5460,
  40353. -0.4776, 0.2847, -0.0271
  40354. ];
  40355. var samplesFactor = 1.0 / numSamples;
  40356. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  40357. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  40358. "area", "fallOff", "base"
  40359. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  40360. this._ssaoPostProcess.onApply = function (effect) {
  40361. if (_this._firstUpdate) {
  40362. effect.setArray3("sampleSphere", sampleSphere);
  40363. effect.setFloat("samplesFactor", samplesFactor);
  40364. effect.setFloat("randTextureTiles", 4.0);
  40365. _this._firstUpdate = false;
  40366. }
  40367. effect.setFloat("totalStrength", _this.totalStrength);
  40368. effect.setFloat("radius", _this.radius);
  40369. effect.setFloat("area", _this.area);
  40370. effect.setFloat("fallOff", _this.fallOff);
  40371. effect.setFloat("base", _this.base);
  40372. effect.setTexture("textureSampler", _this._depthTexture);
  40373. effect.setTexture("randomSampler", _this._randomTexture);
  40374. };
  40375. };
  40376. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  40377. var _this = this;
  40378. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40379. this._ssaoCombinePostProcess.onApply = function (effect) {
  40380. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  40381. };
  40382. };
  40383. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  40384. var size = 512;
  40385. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40386. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40387. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40388. var context = this._randomTexture.getContext();
  40389. var rand = function (min, max) {
  40390. return Math.random() * (max - min) + min;
  40391. };
  40392. var randVector = BABYLON.Vector3.Zero();
  40393. for (var x = 0; x < size; x++) {
  40394. for (var y = 0; y < size; y++) {
  40395. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  40396. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  40397. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  40398. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  40399. context.fillRect(x, y, 1, 1);
  40400. }
  40401. }
  40402. this._randomTexture.update(false);
  40403. };
  40404. return SSAORenderingPipeline;
  40405. })(BABYLON.PostProcessRenderPipeline);
  40406. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  40407. })(BABYLON || (BABYLON = {}));
  40408. var BABYLON;
  40409. (function (BABYLON) {
  40410. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  40411. var VolumetricLightScatteringPostProcess = (function (_super) {
  40412. __extends(VolumetricLightScatteringPostProcess, _super);
  40413. /**
  40414. * @constructor
  40415. * @param {string} name - The post-process name
  40416. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  40417. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  40418. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  40419. * @param {number} samples - The post-process quality, default 100
  40420. * @param {number} samplingMode - The post-process filtering mode
  40421. * @param {BABYLON.Engine} engine - The babylon engine
  40422. * @param {boolean} reusable - If the post-process is reusable
  40423. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  40424. */
  40425. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  40426. var _this = this;
  40427. if (samples === void 0) { samples = 100; }
  40428. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40429. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  40430. this._screenCoordinates = BABYLON.Vector2.Zero();
  40431. /**
  40432. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  40433. * @type {Vector3}
  40434. */
  40435. this.customMeshPosition = BABYLON.Vector3.Zero();
  40436. /**
  40437. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  40438. * @type {boolean}
  40439. */
  40440. this.useCustomMeshPosition = false;
  40441. /**
  40442. * If the post-process should inverse the light scattering direction
  40443. * @type {boolean}
  40444. */
  40445. this.invert = true;
  40446. /**
  40447. * Array containing the excluded meshes not rendered in the internal pass
  40448. */
  40449. this.excludedMeshes = new Array();
  40450. /**
  40451. * Controls the overall intensity of the post-process
  40452. * @type {number}
  40453. */
  40454. this.exposure = 0.3;
  40455. /**
  40456. * Dissipates each sample's contribution in range [0, 1]
  40457. * @type {number}
  40458. */
  40459. this.decay = 0.96815;
  40460. /**
  40461. * Controls the overall intensity of each sample
  40462. * @type {number}
  40463. */
  40464. this.weight = 0.58767;
  40465. /**
  40466. * Controls the density of each sample
  40467. * @type {number}
  40468. */
  40469. this.density = 0.926;
  40470. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  40471. var engine = scene.getEngine();
  40472. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  40473. // Configure mesh
  40474. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  40475. // Configure
  40476. this._createPass(scene, ratio.passRatio || ratio);
  40477. this.onActivate = function (camera) {
  40478. if (!_this.isSupported) {
  40479. _this.dispose(camera);
  40480. }
  40481. _this.onActivate = null;
  40482. };
  40483. this.onApply = function (effect) {
  40484. _this._updateMeshScreenCoordinates(scene);
  40485. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  40486. effect.setFloat("exposure", _this.exposure);
  40487. effect.setFloat("decay", _this.decay);
  40488. effect.setFloat("weight", _this.weight);
  40489. effect.setFloat("density", _this.density);
  40490. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  40491. };
  40492. }
  40493. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  40494. get: function () {
  40495. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  40496. return false;
  40497. },
  40498. set: function (useDiffuseColor) {
  40499. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  40500. },
  40501. enumerable: true,
  40502. configurable: true
  40503. });
  40504. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  40505. var mesh = subMesh.getMesh();
  40506. // Render this.mesh as default
  40507. if (mesh === this.mesh) {
  40508. return mesh.material.isReady(mesh);
  40509. }
  40510. var defines = [];
  40511. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40512. var material = subMesh.getMaterial();
  40513. var needUV = false;
  40514. // Alpha test
  40515. if (material) {
  40516. if (material.needAlphaTesting()) {
  40517. defines.push("#define ALPHATEST");
  40518. }
  40519. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40520. attribs.push(BABYLON.VertexBuffer.UVKind);
  40521. defines.push("#define UV1");
  40522. }
  40523. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40524. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40525. defines.push("#define UV2");
  40526. }
  40527. }
  40528. // Bones
  40529. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40530. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40531. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40532. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40533. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40534. }
  40535. else {
  40536. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40537. }
  40538. // Instances
  40539. if (useInstances) {
  40540. defines.push("#define INSTANCES");
  40541. attribs.push("world0");
  40542. attribs.push("world1");
  40543. attribs.push("world2");
  40544. attribs.push("world3");
  40545. }
  40546. // Get correct effect
  40547. var join = defines.join("\n");
  40548. if (this._cachedDefines !== join) {
  40549. this._cachedDefines = join;
  40550. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  40551. }
  40552. return this._volumetricLightScatteringPass.isReady();
  40553. };
  40554. /**
  40555. * Sets the new light position for light scattering effect
  40556. * @param {BABYLON.Vector3} The new custom light position
  40557. */
  40558. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  40559. this.customMeshPosition = position;
  40560. };
  40561. /**
  40562. * Returns the light position for light scattering effect
  40563. * @return {BABYLON.Vector3} The custom light position
  40564. */
  40565. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  40566. return this.customMeshPosition;
  40567. };
  40568. /**
  40569. * Disposes the internal assets and detaches the post-process from the camera
  40570. */
  40571. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  40572. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  40573. if (rttIndex !== -1) {
  40574. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  40575. }
  40576. this._volumetricLightScatteringRTT.dispose();
  40577. _super.prototype.dispose.call(this, camera);
  40578. };
  40579. /**
  40580. * Returns the render target texture used by the post-process
  40581. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  40582. */
  40583. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  40584. return this._volumetricLightScatteringRTT;
  40585. };
  40586. // Private methods
  40587. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  40588. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  40589. return true;
  40590. }
  40591. return false;
  40592. };
  40593. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  40594. var _this = this;
  40595. var engine = scene.getEngine();
  40596. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  40597. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40598. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40599. this._volumetricLightScatteringRTT.renderList = null;
  40600. this._volumetricLightScatteringRTT.renderParticles = false;
  40601. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  40602. // Custom render function for submeshes
  40603. var renderSubMesh = function (subMesh) {
  40604. var mesh = subMesh.getRenderingMesh();
  40605. if (_this._meshExcluded(mesh)) {
  40606. return;
  40607. }
  40608. var scene = mesh.getScene();
  40609. var engine = scene.getEngine();
  40610. // Culling
  40611. engine.setState(subMesh.getMaterial().backFaceCulling);
  40612. // Managing instances
  40613. var batch = mesh._getInstancesRenderList(subMesh._id);
  40614. if (batch.mustReturn) {
  40615. return;
  40616. }
  40617. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  40618. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40619. var effect = _this._volumetricLightScatteringPass;
  40620. if (mesh === _this.mesh) {
  40621. effect = subMesh.getMaterial().getEffect();
  40622. }
  40623. engine.enableEffect(effect);
  40624. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  40625. if (mesh === _this.mesh) {
  40626. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  40627. }
  40628. else {
  40629. var material = subMesh.getMaterial();
  40630. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  40631. // Alpha test
  40632. if (material && material.needAlphaTesting()) {
  40633. var alphaTexture = material.getAlphaTestTexture();
  40634. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  40635. if (alphaTexture) {
  40636. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40637. }
  40638. }
  40639. // Bones
  40640. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40641. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40642. }
  40643. }
  40644. // Draw
  40645. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  40646. }
  40647. };
  40648. // Render target texture callbacks
  40649. var savedSceneClearColor;
  40650. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  40651. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  40652. savedSceneClearColor = scene.clearColor;
  40653. scene.clearColor = sceneClearColor;
  40654. };
  40655. this._volumetricLightScatteringRTT.onAfterRender = function () {
  40656. scene.clearColor = savedSceneClearColor;
  40657. };
  40658. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  40659. var engine = scene.getEngine();
  40660. var index;
  40661. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40662. renderSubMesh(opaqueSubMeshes.data[index]);
  40663. }
  40664. engine.setAlphaTesting(true);
  40665. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40666. renderSubMesh(alphaTestSubMeshes.data[index]);
  40667. }
  40668. engine.setAlphaTesting(false);
  40669. if (transparentSubMeshes.length) {
  40670. // Sort sub meshes
  40671. for (index = 0; index < transparentSubMeshes.length; index++) {
  40672. var submesh = transparentSubMeshes.data[index];
  40673. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  40674. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  40675. }
  40676. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  40677. sortedArray.sort(function (a, b) {
  40678. // Alpha index first
  40679. if (a._alphaIndex > b._alphaIndex) {
  40680. return 1;
  40681. }
  40682. if (a._alphaIndex < b._alphaIndex) {
  40683. return -1;
  40684. }
  40685. // Then distance to camera
  40686. if (a._distanceToCamera < b._distanceToCamera) {
  40687. return 1;
  40688. }
  40689. if (a._distanceToCamera > b._distanceToCamera) {
  40690. return -1;
  40691. }
  40692. return 0;
  40693. });
  40694. // Render sub meshes
  40695. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40696. for (index = 0; index < sortedArray.length; index++) {
  40697. renderSubMesh(sortedArray[index]);
  40698. }
  40699. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40700. }
  40701. };
  40702. };
  40703. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  40704. var transform = scene.getTransformMatrix();
  40705. var meshPosition;
  40706. if (this.useCustomMeshPosition) {
  40707. meshPosition = this.customMeshPosition;
  40708. }
  40709. else if (this.attachedNode) {
  40710. meshPosition = this.attachedNode.position;
  40711. }
  40712. else {
  40713. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  40714. }
  40715. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  40716. this._screenCoordinates.x = pos.x / this._viewPort.width;
  40717. this._screenCoordinates.y = pos.y / this._viewPort.height;
  40718. if (this.invert)
  40719. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  40720. };
  40721. // Static methods
  40722. /**
  40723. * Creates a default mesh for the Volumeric Light Scattering post-process
  40724. * @param {string} The mesh name
  40725. * @param {BABYLON.Scene} The scene where to create the mesh
  40726. * @return {BABYLON.Mesh} the default mesh
  40727. */
  40728. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  40729. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  40730. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  40731. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  40732. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  40733. mesh.material = material;
  40734. return mesh;
  40735. };
  40736. __decorate([
  40737. BABYLON.serializeAsVector3()
  40738. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  40739. __decorate([
  40740. BABYLON.serialize()
  40741. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  40742. __decorate([
  40743. BABYLON.serialize()
  40744. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  40745. __decorate([
  40746. BABYLON.serializeAsMeshReference()
  40747. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  40748. __decorate([
  40749. BABYLON.serialize()
  40750. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  40751. __decorate([
  40752. BABYLON.serialize()
  40753. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  40754. __decorate([
  40755. BABYLON.serialize()
  40756. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  40757. __decorate([
  40758. BABYLON.serialize()
  40759. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  40760. __decorate([
  40761. BABYLON.serialize()
  40762. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  40763. return VolumetricLightScatteringPostProcess;
  40764. })(BABYLON.PostProcess);
  40765. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  40766. })(BABYLON || (BABYLON = {}));
  40767. // BABYLON.JS Chromatic Aberration GLSL Shader
  40768. // Author: Olivier Guyot
  40769. // Separates very slightly R, G and B colors on the edges of the screen
  40770. // Inspired by Francois Tarlier & Martins Upitis
  40771. var BABYLON;
  40772. (function (BABYLON) {
  40773. var LensRenderingPipeline = (function (_super) {
  40774. __extends(LensRenderingPipeline, _super);
  40775. /**
  40776. * @constructor
  40777. *
  40778. * Effect parameters are as follow:
  40779. * {
  40780. * chromatic_aberration: number; // from 0 to x (1 for realism)
  40781. * edge_blur: number; // from 0 to x (1 for realism)
  40782. * distortion: number; // from 0 to x (1 for realism)
  40783. * grain_amount: number; // from 0 to 1
  40784. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  40785. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  40786. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  40787. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  40788. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  40789. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  40790. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  40791. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  40792. * }
  40793. * Note: if an effect parameter is unset, effect is disabled
  40794. *
  40795. * @param {string} name - The rendering pipeline name
  40796. * @param {object} parameters - An object containing all parameters (see above)
  40797. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40798. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  40799. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40800. */
  40801. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  40802. var _this = this;
  40803. if (ratio === void 0) { ratio = 1.0; }
  40804. _super.call(this, scene.getEngine(), name);
  40805. // Lens effects can be of the following:
  40806. // - chromatic aberration (slight shift of RGB colors)
  40807. // - blur on the edge of the lens
  40808. // - lens distortion
  40809. // - depth-of-field blur & highlights enhancing
  40810. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  40811. // - grain effect (noise or custom texture)
  40812. // Two additional texture samplers are needed:
  40813. // - depth map (for depth-of-field)
  40814. // - grain texture
  40815. /**
  40816. * The chromatic aberration PostProcess id in the pipeline
  40817. * @type {string}
  40818. */
  40819. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  40820. /**
  40821. * The highlights enhancing PostProcess id in the pipeline
  40822. * @type {string}
  40823. */
  40824. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  40825. /**
  40826. * The depth-of-field PostProcess id in the pipeline
  40827. * @type {string}
  40828. */
  40829. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  40830. this._scene = scene;
  40831. // Fetch texture samplers
  40832. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  40833. if (parameters.grain_texture) {
  40834. this._grainTexture = parameters.grain_texture;
  40835. }
  40836. else {
  40837. this._createGrainTexture();
  40838. }
  40839. // save parameters
  40840. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  40841. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  40842. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  40843. this._distortion = parameters.distortion ? parameters.distortion : 0;
  40844. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  40845. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  40846. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  40847. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  40848. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  40849. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  40850. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  40851. // Create effects
  40852. this._createChromaticAberrationPostProcess(ratio);
  40853. this._createHighlightsPostProcess(ratio);
  40854. this._createDepthOfFieldPostProcess(ratio / 4);
  40855. // Set up pipeline
  40856. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  40857. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  40858. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  40859. if (this._highlightsGain === -1) {
  40860. this._disableEffect(this.HighlightsEnhancingEffect, null);
  40861. }
  40862. // Finish
  40863. scene.postProcessRenderPipelineManager.addPipeline(this);
  40864. if (cameras) {
  40865. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40866. }
  40867. }
  40868. // public methods (self explanatory)
  40869. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  40870. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  40871. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  40872. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  40873. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  40874. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  40875. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  40876. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  40877. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  40878. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  40879. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  40880. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  40881. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  40882. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  40883. };
  40884. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  40885. this._highlightsPostProcess.updateEffect();
  40886. };
  40887. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  40888. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  40889. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  40890. this._highlightsGain = amount;
  40891. };
  40892. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  40893. if (this._highlightsGain === -1) {
  40894. this._highlightsGain = 1.0;
  40895. }
  40896. this._highlightsThreshold = amount;
  40897. };
  40898. LensRenderingPipeline.prototype.disableHighlights = function () {
  40899. this._highlightsGain = -1;
  40900. };
  40901. /**
  40902. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  40903. */
  40904. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  40905. if (disableDepthRender === void 0) { disableDepthRender = false; }
  40906. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40907. this._chromaticAberrationPostProcess = undefined;
  40908. this._highlightsPostProcess = undefined;
  40909. this._depthOfFieldPostProcess = undefined;
  40910. this._grainTexture.dispose();
  40911. if (disableDepthRender)
  40912. this._scene.disableDepthRenderer();
  40913. };
  40914. // colors shifting and distortion
  40915. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  40916. var _this = this;
  40917. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  40918. [], // samplers
  40919. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40920. this._chromaticAberrationPostProcess.onApply = function (effect) {
  40921. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  40922. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40923. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40924. };
  40925. };
  40926. // highlights enhancing
  40927. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  40928. var _this = this;
  40929. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  40930. [], // samplers
  40931. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  40932. this._highlightsPostProcess.onApply = function (effect) {
  40933. effect.setFloat('gain', _this._highlightsGain);
  40934. effect.setFloat('threshold', _this._highlightsThreshold);
  40935. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  40936. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40937. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40938. };
  40939. };
  40940. // colors shifting and distortion
  40941. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  40942. var _this = this;
  40943. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  40944. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  40945. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  40946. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40947. this._depthOfFieldPostProcess.onApply = function (effect) {
  40948. effect.setTexture("depthSampler", _this._depthTexture);
  40949. effect.setTexture("grainSampler", _this._grainTexture);
  40950. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  40951. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  40952. effect.setFloat('grain_amount', _this._grainAmount);
  40953. effect.setBool('blur_noise', _this._blurNoise);
  40954. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40955. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40956. effect.setFloat('distortion', _this._distortion);
  40957. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  40958. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  40959. effect.setFloat('aperture', _this._dofAperture);
  40960. effect.setFloat('darken', _this._dofDarken);
  40961. effect.setFloat('edge_blur', _this._edgeBlur);
  40962. effect.setBool('highlights', (_this._highlightsGain !== -1));
  40963. effect.setFloat('near', _this._scene.activeCamera.minZ);
  40964. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  40965. };
  40966. };
  40967. // creates a black and white random noise texture, 512x512
  40968. LensRenderingPipeline.prototype._createGrainTexture = function () {
  40969. var size = 512;
  40970. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40971. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40972. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40973. var context = this._grainTexture.getContext();
  40974. var rand = function (min, max) {
  40975. return Math.random() * (max - min) + min;
  40976. };
  40977. var value;
  40978. for (var x = 0; x < size; x++) {
  40979. for (var y = 0; y < size; y++) {
  40980. value = Math.floor(rand(0.42, 0.58) * 255);
  40981. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  40982. context.fillRect(x, y, 1, 1);
  40983. }
  40984. }
  40985. this._grainTexture.update(false);
  40986. };
  40987. return LensRenderingPipeline;
  40988. })(BABYLON.PostProcessRenderPipeline);
  40989. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  40990. })(BABYLON || (BABYLON = {}));
  40991. //
  40992. // This post-process allows the modification of rendered colors by using
  40993. // a 'look-up table' (LUT). This effect is also called Color Grading.
  40994. //
  40995. // The object needs to be provided an url to a texture containing the color
  40996. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  40997. // Use an image editing software to tweak the LUT to match your needs.
  40998. //
  40999. // For an example of a color LUT, see here:
  41000. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  41001. // For explanations on color grading, see here:
  41002. // http://udn.epicgames.com/Three/ColorGrading.html
  41003. //
  41004. var BABYLON;
  41005. (function (BABYLON) {
  41006. var ColorCorrectionPostProcess = (function (_super) {
  41007. __extends(ColorCorrectionPostProcess, _super);
  41008. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  41009. var _this = this;
  41010. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  41011. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  41012. this._colorTableTexture.anisotropicFilteringLevel = 1;
  41013. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41014. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41015. this.onApply = function (effect) {
  41016. effect.setTexture("colorTable", _this._colorTableTexture);
  41017. };
  41018. }
  41019. return ColorCorrectionPostProcess;
  41020. })(BABYLON.PostProcess);
  41021. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  41022. })(BABYLON || (BABYLON = {}));
  41023. var BABYLON;
  41024. (function (BABYLON) {
  41025. var AnaglyphFreeCamera = (function (_super) {
  41026. __extends(AnaglyphFreeCamera, _super);
  41027. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  41028. _super.call(this, name, position, scene);
  41029. this.interaxialDistance = interaxialDistance;
  41030. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41031. }
  41032. AnaglyphFreeCamera.prototype.getTypeName = function () {
  41033. return "AnaglyphFreeCamera";
  41034. };
  41035. return AnaglyphFreeCamera;
  41036. })(BABYLON.FreeCamera);
  41037. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  41038. var AnaglyphArcRotateCamera = (function (_super) {
  41039. __extends(AnaglyphArcRotateCamera, _super);
  41040. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  41041. _super.call(this, name, alpha, beta, radius, target, scene);
  41042. this.interaxialDistance = interaxialDistance;
  41043. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41044. }
  41045. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  41046. return "AnaglyphArcRotateCamera";
  41047. };
  41048. return AnaglyphArcRotateCamera;
  41049. })(BABYLON.ArcRotateCamera);
  41050. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  41051. var AnaglyphGamepadCamera = (function (_super) {
  41052. __extends(AnaglyphGamepadCamera, _super);
  41053. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  41054. _super.call(this, name, position, scene);
  41055. this.interaxialDistance = interaxialDistance;
  41056. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41057. }
  41058. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  41059. return "AnaglyphGamepadCamera";
  41060. };
  41061. return AnaglyphGamepadCamera;
  41062. })(BABYLON.GamepadCamera);
  41063. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  41064. var AnaglyphUniversalCamera = (function (_super) {
  41065. __extends(AnaglyphUniversalCamera, _super);
  41066. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  41067. _super.call(this, name, position, scene);
  41068. this.interaxialDistance = interaxialDistance;
  41069. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41070. }
  41071. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  41072. return "AnaglyphUniversalCamera";
  41073. };
  41074. return AnaglyphUniversalCamera;
  41075. })(BABYLON.UniversalCamera);
  41076. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  41077. var StereoscopicFreeCamera = (function (_super) {
  41078. __extends(StereoscopicFreeCamera, _super);
  41079. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  41080. _super.call(this, name, position, scene);
  41081. this.interaxialDistance = interaxialDistance;
  41082. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41083. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41084. }
  41085. StereoscopicFreeCamera.prototype.getTypeName = function () {
  41086. return "StereoscopicFreeCamera";
  41087. };
  41088. return StereoscopicFreeCamera;
  41089. })(BABYLON.FreeCamera);
  41090. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  41091. var StereoscopicArcRotateCamera = (function (_super) {
  41092. __extends(StereoscopicArcRotateCamera, _super);
  41093. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  41094. _super.call(this, name, alpha, beta, radius, target, scene);
  41095. this.interaxialDistance = interaxialDistance;
  41096. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41097. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41098. }
  41099. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  41100. return "StereoscopicArcRotateCamera";
  41101. };
  41102. return StereoscopicArcRotateCamera;
  41103. })(BABYLON.ArcRotateCamera);
  41104. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  41105. var StereoscopicGamepadCamera = (function (_super) {
  41106. __extends(StereoscopicGamepadCamera, _super);
  41107. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  41108. _super.call(this, name, position, scene);
  41109. this.interaxialDistance = interaxialDistance;
  41110. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41111. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41112. }
  41113. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  41114. return "StereoscopicGamepadCamera";
  41115. };
  41116. return StereoscopicGamepadCamera;
  41117. })(BABYLON.GamepadCamera);
  41118. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  41119. var StereoscopicUniversalCamera = (function (_super) {
  41120. __extends(StereoscopicUniversalCamera, _super);
  41121. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  41122. _super.call(this, name, position, scene);
  41123. this.interaxialDistance = interaxialDistance;
  41124. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41125. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41126. }
  41127. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  41128. return "StereoscopicUniversalCamera";
  41129. };
  41130. return StereoscopicUniversalCamera;
  41131. })(BABYLON.UniversalCamera);
  41132. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  41133. })(BABYLON || (BABYLON = {}));
  41134. var BABYLON;
  41135. (function (BABYLON) {
  41136. var HDRRenderingPipeline = (function (_super) {
  41137. __extends(HDRRenderingPipeline, _super);
  41138. /**
  41139. * @constructor
  41140. * @param {string} name - The rendering pipeline name
  41141. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  41142. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  41143. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  41144. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  41145. */
  41146. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  41147. var _this = this;
  41148. if (originalPostProcess === void 0) { originalPostProcess = null; }
  41149. _super.call(this, scene.getEngine(), name);
  41150. /**
  41151. * Public members
  41152. */
  41153. // Gaussian Blur
  41154. /**
  41155. * Gaussian blur coefficient
  41156. * @type {number}
  41157. */
  41158. this.gaussCoeff = 0.3;
  41159. /**
  41160. * Gaussian blur mean
  41161. * @type {number}
  41162. */
  41163. this.gaussMean = 1.0;
  41164. /**
  41165. * Gaussian blur standard deviation
  41166. * @type {number}
  41167. */
  41168. this.gaussStandDev = 0.8;
  41169. /**
  41170. * Gaussian blur multiplier. Multiplies the blur effect
  41171. * @type {number}
  41172. */
  41173. this.gaussMultiplier = 4.0;
  41174. // HDR
  41175. /**
  41176. * Exposure, controls the overall intensity of the pipeline
  41177. * @type {number}
  41178. */
  41179. this.exposure = 1.0;
  41180. /**
  41181. * Minimum luminance that the post-process can output. Luminance is >= 0
  41182. * @type {number}
  41183. */
  41184. this.minimumLuminance = 1.0;
  41185. /**
  41186. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  41187. * @type {number}
  41188. */
  41189. this.maximumLuminance = 1e20;
  41190. /**
  41191. * Increase rate for luminance: eye adaptation speed to dark
  41192. * @type {number}
  41193. */
  41194. this.luminanceIncreaserate = 0.5;
  41195. /**
  41196. * Decrease rate for luminance: eye adaptation speed to bright
  41197. * @type {number}
  41198. */
  41199. this.luminanceDecreaseRate = 0.5;
  41200. // Bright pass
  41201. /**
  41202. * Minimum luminance needed to compute HDR
  41203. * @type {number}
  41204. */
  41205. this.brightThreshold = 0.8;
  41206. this._needUpdate = true;
  41207. this._scene = scene;
  41208. // Bright pass
  41209. this._createBrightPassPostProcess(scene, ratio);
  41210. // Down sample X4
  41211. this._createDownSampleX4PostProcess(scene, ratio);
  41212. // Create gaussian blur post-processes
  41213. this._createGaussianBlurPostProcess(scene, ratio);
  41214. // Texture adder
  41215. this._createTextureAdderPostProcess(scene, ratio);
  41216. // Luminance generator
  41217. this._createLuminanceGeneratorPostProcess(scene);
  41218. // HDR
  41219. this._createHDRPostProcess(scene, ratio);
  41220. // Pass postprocess
  41221. if (originalPostProcess === null) {
  41222. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  41223. }
  41224. else {
  41225. this._originalPostProcess = originalPostProcess;
  41226. }
  41227. // Configure pipeline
  41228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  41229. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  41230. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  41231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  41232. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  41233. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  41234. var addDownSamplerPostProcess = function (id) {
  41235. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  41236. };
  41237. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  41238. addDownSamplerPostProcess(i);
  41239. }
  41240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  41241. // Finish
  41242. scene.postProcessRenderPipelineManager.addPipeline(this);
  41243. if (cameras !== null) {
  41244. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  41245. }
  41246. this.update();
  41247. }
  41248. /**
  41249. * Tells the pipeline to update its post-processes
  41250. */
  41251. HDRRenderingPipeline.prototype.update = function () {
  41252. this._needUpdate = true;
  41253. };
  41254. /**
  41255. * Returns the current calculated luminance
  41256. */
  41257. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  41258. return this._hdrCurrentLuminance;
  41259. };
  41260. /**
  41261. * Returns the currently drawn luminance
  41262. */
  41263. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  41264. return this._hdrOutputLuminance;
  41265. };
  41266. /**
  41267. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  41268. */
  41269. HDRRenderingPipeline.prototype.dispose = function () {
  41270. this._originalPostProcess = undefined;
  41271. this._brightPassPostProcess = undefined;
  41272. this._downSampleX4PostProcess = undefined;
  41273. this._guassianBlurHPostProcess = undefined;
  41274. this._guassianBlurVPostProcess = undefined;
  41275. this._textureAdderPostProcess = undefined;
  41276. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  41277. this._downSamplePostProcesses[i] = undefined;
  41278. }
  41279. this._hdrPostProcess = undefined;
  41280. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  41281. };
  41282. /**
  41283. * Creates the HDR post-process and computes the luminance adaptation
  41284. */
  41285. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  41286. var _this = this;
  41287. var hdrLastLuminance = 0.0;
  41288. this._hdrOutputLuminance = -1.0;
  41289. this._hdrCurrentLuminance = 1.0;
  41290. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  41291. this._hdrPostProcess.onApply = function (effect) {
  41292. if (_this._hdrOutputLuminance < 0.0) {
  41293. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  41294. }
  41295. else {
  41296. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  41297. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  41298. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  41299. }
  41300. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  41301. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  41302. }
  41303. else {
  41304. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  41305. }
  41306. }
  41307. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  41308. hdrLastLuminance += scene.getEngine().getDeltaTime();
  41309. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  41310. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  41311. effect.setFloat("exposure", _this.exposure);
  41312. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  41313. _this._needUpdate = false;
  41314. };
  41315. };
  41316. /**
  41317. * Texture Adder post-process
  41318. */
  41319. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  41320. var _this = this;
  41321. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  41322. this._textureAdderPostProcess.onApply = function (effect) {
  41323. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  41324. };
  41325. };
  41326. /**
  41327. * Down sample X4 post-process
  41328. */
  41329. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  41330. var _this = this;
  41331. var downSampleX4Offsets = new Array(32);
  41332. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  41333. this._downSampleX4PostProcess.onApply = function (effect) {
  41334. if (_this._needUpdate) {
  41335. var id = 0;
  41336. for (var i = -2; i < 2; i++) {
  41337. for (var j = -2; j < 2; j++) {
  41338. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  41339. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  41340. id += 2;
  41341. }
  41342. }
  41343. }
  41344. effect.setArray2("dsOffsets", downSampleX4Offsets);
  41345. };
  41346. };
  41347. /**
  41348. * Bright pass post-process
  41349. */
  41350. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  41351. var _this = this;
  41352. var brightOffsets = new Array(8);
  41353. var brightPassCallback = function (effect) {
  41354. if (_this._needUpdate) {
  41355. var sU = (1.0 / _this._brightPassPostProcess.width);
  41356. var sV = (1.0 / _this._brightPassPostProcess.height);
  41357. brightOffsets[0] = -0.5 * sU;
  41358. brightOffsets[1] = 0.5 * sV;
  41359. brightOffsets[2] = 0.5 * sU;
  41360. brightOffsets[3] = 0.5 * sV;
  41361. brightOffsets[4] = -0.5 * sU;
  41362. brightOffsets[5] = -0.5 * sV;
  41363. brightOffsets[6] = 0.5 * sU;
  41364. brightOffsets[7] = -0.5 * sV;
  41365. }
  41366. effect.setArray2("dsOffsets", brightOffsets);
  41367. effect.setFloat("brightThreshold", _this.brightThreshold);
  41368. };
  41369. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  41370. this._brightPassPostProcess.onApply = brightPassCallback;
  41371. };
  41372. /**
  41373. * Luminance generator. Creates the luminance post-process and down sample post-processes
  41374. */
  41375. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  41376. var _this = this;
  41377. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  41378. var luminanceOffsets = new Array(8);
  41379. var downSampleOffsets = new Array(18);
  41380. var halfDestPixelSize;
  41381. this._downSamplePostProcesses = new Array(lumSteps);
  41382. // Utils for luminance
  41383. var luminanceUpdateSourceOffsets = function (width, height) {
  41384. var sU = (1.0 / width);
  41385. var sV = (1.0 / height);
  41386. luminanceOffsets[0] = -0.5 * sU;
  41387. luminanceOffsets[1] = 0.5 * sV;
  41388. luminanceOffsets[2] = 0.5 * sU;
  41389. luminanceOffsets[3] = 0.5 * sV;
  41390. luminanceOffsets[4] = -0.5 * sU;
  41391. luminanceOffsets[5] = -0.5 * sV;
  41392. luminanceOffsets[6] = 0.5 * sU;
  41393. luminanceOffsets[7] = -0.5 * sV;
  41394. };
  41395. var luminanceUpdateDestOffsets = function (width, height) {
  41396. var id = 0;
  41397. for (var x = -1; x < 2; x++) {
  41398. for (var y = -1; y < 2; y++) {
  41399. downSampleOffsets[id] = (x) / width;
  41400. downSampleOffsets[id + 1] = (y) / height;
  41401. id += 2;
  41402. }
  41403. }
  41404. };
  41405. // Luminance callback
  41406. var luminanceCallback = function (effect) {
  41407. if (_this._needUpdate) {
  41408. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  41409. }
  41410. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  41411. effect.setArray2("lumOffsets", luminanceOffsets);
  41412. };
  41413. // Down sample callbacks
  41414. var downSampleCallback = function (indice) {
  41415. var i = indice;
  41416. return function (effect) {
  41417. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  41418. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  41419. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  41420. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  41421. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  41422. effect.setArray2("dsOffsets", downSampleOffsets);
  41423. };
  41424. };
  41425. var downSampleAfterRenderCallback = function (effect) {
  41426. // Unpack result
  41427. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  41428. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  41429. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  41430. };
  41431. // Create luminance post-process
  41432. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  41433. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  41434. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  41435. // Create down sample post-processes
  41436. for (var i = lumSteps - 2; i >= 0; i--) {
  41437. var length = Math.pow(3, i);
  41438. ratio = { width: length, height: length };
  41439. var defines = "#define DOWN_SAMPLE\n";
  41440. if (i === 0) {
  41441. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  41442. }
  41443. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  41444. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  41445. if (i === 0) {
  41446. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  41447. }
  41448. }
  41449. };
  41450. /**
  41451. * Gaussian blur post-processes. Horizontal and Vertical
  41452. */
  41453. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  41454. var _this = this;
  41455. var blurOffsetsW = new Array(9);
  41456. var blurOffsetsH = new Array(9);
  41457. var blurWeights = new Array(9);
  41458. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  41459. // Utils for gaussian blur
  41460. var calculateBlurOffsets = function (height) {
  41461. var lastOutputDimensions = {
  41462. width: scene.getEngine().getRenderWidth(),
  41463. height: scene.getEngine().getRenderHeight()
  41464. };
  41465. for (var i = 0; i < 9; i++) {
  41466. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  41467. if (height) {
  41468. blurOffsetsH[i] = value;
  41469. }
  41470. else {
  41471. blurOffsetsW[i] = value;
  41472. }
  41473. }
  41474. };
  41475. var calculateWeights = function () {
  41476. var x = 0.0;
  41477. for (var i = 0; i < 9; i++) {
  41478. x = (i - 4.0) / 4.0;
  41479. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  41480. }
  41481. };
  41482. // Callback
  41483. var gaussianBlurCallback = function (height) {
  41484. return function (effect) {
  41485. if (_this._needUpdate) {
  41486. calculateWeights();
  41487. calculateBlurOffsets(height);
  41488. }
  41489. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  41490. effect.setArray("blurWeights", blurWeights);
  41491. effect.setFloat("multiplier", _this.gaussMultiplier);
  41492. };
  41493. };
  41494. // Create horizontal gaussian blur post-processes
  41495. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  41496. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  41497. // Create vertical gaussian blur post-process
  41498. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  41499. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  41500. };
  41501. // Luminance generator
  41502. HDRRenderingPipeline.LUM_STEPS = 6;
  41503. return HDRRenderingPipeline;
  41504. })(BABYLON.PostProcessRenderPipeline);
  41505. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  41506. })(BABYLON || (BABYLON = {}));
  41507. var BABYLON;
  41508. (function (BABYLON) {
  41509. var FaceAdjacencies = (function () {
  41510. function FaceAdjacencies() {
  41511. this.edges = new Array();
  41512. this.edgesConnectedCount = 0;
  41513. }
  41514. return FaceAdjacencies;
  41515. })();
  41516. var EdgesRenderer = (function () {
  41517. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  41518. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  41519. if (epsilon === void 0) { epsilon = 0.95; }
  41520. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  41521. this.edgesWidthScalerForOrthographic = 1000.0;
  41522. this.edgesWidthScalerForPerspective = 50.0;
  41523. this._linesPositions = new Array();
  41524. this._linesNormals = new Array();
  41525. this._linesIndices = new Array();
  41526. this._buffers = new Array();
  41527. this._checkVerticesInsteadOfIndices = false;
  41528. this._source = source;
  41529. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  41530. this._epsilon = epsilon;
  41531. this._prepareRessources();
  41532. this._generateEdgesLines();
  41533. }
  41534. EdgesRenderer.prototype._prepareRessources = function () {
  41535. if (this._lineShader) {
  41536. return;
  41537. }
  41538. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  41539. attributes: ["position", "normal"],
  41540. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  41541. });
  41542. this._lineShader.disableDepthWrite = true;
  41543. this._lineShader.backFaceCulling = false;
  41544. };
  41545. EdgesRenderer.prototype.dispose = function () {
  41546. this._vb0.dispose();
  41547. this._vb1.dispose();
  41548. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  41549. this._lineShader.dispose();
  41550. };
  41551. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  41552. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  41553. return 0;
  41554. }
  41555. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  41556. return 1;
  41557. }
  41558. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  41559. return 2;
  41560. }
  41561. return -1;
  41562. };
  41563. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  41564. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  41565. return 0;
  41566. }
  41567. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  41568. return 1;
  41569. }
  41570. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  41571. return 2;
  41572. }
  41573. return -1;
  41574. };
  41575. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  41576. var needToCreateLine;
  41577. if (edge === undefined) {
  41578. needToCreateLine = true;
  41579. }
  41580. else {
  41581. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  41582. needToCreateLine = dotProduct < this._epsilon;
  41583. }
  41584. if (needToCreateLine) {
  41585. var offset = this._linesPositions.length / 3;
  41586. var normal = p0.subtract(p1);
  41587. normal.normalize();
  41588. // Positions
  41589. this._linesPositions.push(p0.x);
  41590. this._linesPositions.push(p0.y);
  41591. this._linesPositions.push(p0.z);
  41592. this._linesPositions.push(p0.x);
  41593. this._linesPositions.push(p0.y);
  41594. this._linesPositions.push(p0.z);
  41595. this._linesPositions.push(p1.x);
  41596. this._linesPositions.push(p1.y);
  41597. this._linesPositions.push(p1.z);
  41598. this._linesPositions.push(p1.x);
  41599. this._linesPositions.push(p1.y);
  41600. this._linesPositions.push(p1.z);
  41601. // Normals
  41602. this._linesNormals.push(p1.x);
  41603. this._linesNormals.push(p1.y);
  41604. this._linesNormals.push(p1.z);
  41605. this._linesNormals.push(-1);
  41606. this._linesNormals.push(p1.x);
  41607. this._linesNormals.push(p1.y);
  41608. this._linesNormals.push(p1.z);
  41609. this._linesNormals.push(1);
  41610. this._linesNormals.push(p0.x);
  41611. this._linesNormals.push(p0.y);
  41612. this._linesNormals.push(p0.z);
  41613. this._linesNormals.push(-1);
  41614. this._linesNormals.push(p0.x);
  41615. this._linesNormals.push(p0.y);
  41616. this._linesNormals.push(p0.z);
  41617. this._linesNormals.push(1);
  41618. // Indices
  41619. this._linesIndices.push(offset);
  41620. this._linesIndices.push(offset + 1);
  41621. this._linesIndices.push(offset + 2);
  41622. this._linesIndices.push(offset);
  41623. this._linesIndices.push(offset + 2);
  41624. this._linesIndices.push(offset + 3);
  41625. }
  41626. };
  41627. EdgesRenderer.prototype._generateEdgesLines = function () {
  41628. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41629. var indices = this._source.getIndices();
  41630. // First let's find adjacencies
  41631. var adjacencies = new Array();
  41632. var faceNormals = new Array();
  41633. var index;
  41634. var faceAdjacencies;
  41635. // Prepare faces
  41636. for (index = 0; index < indices.length; index += 3) {
  41637. faceAdjacencies = new FaceAdjacencies();
  41638. var p0Index = indices[index];
  41639. var p1Index = indices[index + 1];
  41640. var p2Index = indices[index + 2];
  41641. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  41642. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  41643. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  41644. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  41645. faceNormal.normalize();
  41646. faceNormals.push(faceNormal);
  41647. adjacencies.push(faceAdjacencies);
  41648. }
  41649. // Scan
  41650. for (index = 0; index < adjacencies.length; index++) {
  41651. faceAdjacencies = adjacencies[index];
  41652. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  41653. var otherFaceAdjacencies = adjacencies[otherIndex];
  41654. if (faceAdjacencies.edgesConnectedCount === 3) {
  41655. break;
  41656. }
  41657. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  41658. continue;
  41659. }
  41660. var otherP0 = indices[otherIndex * 3];
  41661. var otherP1 = indices[otherIndex * 3 + 1];
  41662. var otherP2 = indices[otherIndex * 3 + 2];
  41663. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  41664. var otherEdgeIndex;
  41665. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  41666. continue;
  41667. }
  41668. switch (edgeIndex) {
  41669. case 0:
  41670. if (this._checkVerticesInsteadOfIndices) {
  41671. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41672. }
  41673. else {
  41674. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  41675. }
  41676. break;
  41677. case 1:
  41678. if (this._checkVerticesInsteadOfIndices) {
  41679. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41680. }
  41681. else {
  41682. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  41683. }
  41684. break;
  41685. case 2:
  41686. if (this._checkVerticesInsteadOfIndices) {
  41687. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41688. }
  41689. else {
  41690. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  41691. }
  41692. break;
  41693. }
  41694. if (otherEdgeIndex === -1) {
  41695. continue;
  41696. }
  41697. faceAdjacencies.edges[edgeIndex] = otherIndex;
  41698. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  41699. faceAdjacencies.edgesConnectedCount++;
  41700. otherFaceAdjacencies.edgesConnectedCount++;
  41701. if (faceAdjacencies.edgesConnectedCount === 3) {
  41702. break;
  41703. }
  41704. }
  41705. }
  41706. }
  41707. // Create lines
  41708. for (index = 0; index < adjacencies.length; index++) {
  41709. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  41710. var current = adjacencies[index];
  41711. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  41712. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  41713. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  41714. }
  41715. // Merge into a single mesh
  41716. var engine = this._source.getScene().getEngine();
  41717. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  41718. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  41719. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  41720. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  41721. this._ib = engine.createIndexBuffer(this._linesIndices);
  41722. this._indicesCount = this._linesIndices.length;
  41723. };
  41724. EdgesRenderer.prototype.render = function () {
  41725. if (!this._lineShader.isReady()) {
  41726. return;
  41727. }
  41728. var scene = this._source.getScene();
  41729. var engine = scene.getEngine();
  41730. this._lineShader._preBind();
  41731. // VBOs
  41732. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  41733. scene.resetCachedMaterial();
  41734. this._lineShader.setColor4("color", this._source.edgesColor);
  41735. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  41736. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  41737. }
  41738. else {
  41739. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  41740. }
  41741. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  41742. this._lineShader.bind(this._source.getWorldMatrix());
  41743. // Draw order
  41744. engine.draw(true, 0, this._indicesCount);
  41745. this._lineShader.unbind();
  41746. engine.setDepthWrite(true);
  41747. };
  41748. return EdgesRenderer;
  41749. })();
  41750. BABYLON.EdgesRenderer = EdgesRenderer;
  41751. })(BABYLON || (BABYLON = {}));
  41752. var BABYLON;
  41753. (function (BABYLON) {
  41754. (function (TonemappingOperator) {
  41755. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  41756. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  41757. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  41758. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  41759. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  41760. var TonemappingOperator = BABYLON.TonemappingOperator;
  41761. ;
  41762. var TonemapPostProcess = (function (_super) {
  41763. __extends(TonemapPostProcess, _super);
  41764. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  41765. var _this = this;
  41766. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41767. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41768. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  41769. this._operator = _operator;
  41770. this.exposureAdjustment = exposureAdjustment;
  41771. var defines = "#define ";
  41772. if (this._operator === TonemappingOperator.Hable)
  41773. defines += "HABLE_TONEMAPPING";
  41774. else if (this._operator === TonemappingOperator.Reinhard)
  41775. defines += "REINHARD_TONEMAPPING";
  41776. else if (this._operator === TonemappingOperator.HejiDawson)
  41777. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  41778. else if (this._operator === TonemappingOperator.Photographic)
  41779. defines += "PHOTOGRAPHIC_TONEMAPPING";
  41780. //sadly a second call to create the effect.
  41781. this.updateEffect(defines);
  41782. this.onApply = function (effect) {
  41783. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  41784. };
  41785. }
  41786. return TonemapPostProcess;
  41787. })(BABYLON.PostProcess);
  41788. BABYLON.TonemapPostProcess = TonemapPostProcess;
  41789. })(BABYLON || (BABYLON = {}));
  41790. var BABYLON;
  41791. (function (BABYLON) {
  41792. var ReflectionProbe = (function () {
  41793. function ReflectionProbe(name, size, scene, generateMipMaps) {
  41794. var _this = this;
  41795. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41796. this.name = name;
  41797. this._viewMatrix = BABYLON.Matrix.Identity();
  41798. this._target = BABYLON.Vector3.Zero();
  41799. this._add = BABYLON.Vector3.Zero();
  41800. this.invertYAxis = false;
  41801. this.position = BABYLON.Vector3.Zero();
  41802. this._scene = scene;
  41803. this._scene.reflectionProbes.push(this);
  41804. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  41805. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  41806. switch (faceIndex) {
  41807. case 0:
  41808. _this._add.copyFromFloats(1, 0, 0);
  41809. break;
  41810. case 1:
  41811. _this._add.copyFromFloats(-1, 0, 0);
  41812. break;
  41813. case 2:
  41814. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  41815. break;
  41816. case 3:
  41817. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  41818. break;
  41819. case 4:
  41820. _this._add.copyFromFloats(0, 0, 1);
  41821. break;
  41822. case 5:
  41823. _this._add.copyFromFloats(0, 0, -1);
  41824. break;
  41825. }
  41826. if (_this._attachedMesh) {
  41827. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  41828. }
  41829. _this.position.addToRef(_this._add, _this._target);
  41830. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  41831. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  41832. };
  41833. this._renderTargetTexture.onAfterUnbind = function () {
  41834. scene.updateTransformMatrix(true);
  41835. };
  41836. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  41837. }
  41838. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  41839. get: function () {
  41840. return this._renderTargetTexture.refreshRate;
  41841. },
  41842. set: function (value) {
  41843. this._renderTargetTexture.refreshRate = value;
  41844. },
  41845. enumerable: true,
  41846. configurable: true
  41847. });
  41848. ReflectionProbe.prototype.getScene = function () {
  41849. return this._scene;
  41850. };
  41851. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  41852. get: function () {
  41853. return this._renderTargetTexture;
  41854. },
  41855. enumerable: true,
  41856. configurable: true
  41857. });
  41858. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  41859. get: function () {
  41860. return this._renderTargetTexture.renderList;
  41861. },
  41862. enumerable: true,
  41863. configurable: true
  41864. });
  41865. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  41866. this._attachedMesh = mesh;
  41867. };
  41868. ReflectionProbe.prototype.dispose = function () {
  41869. var index = this._scene.reflectionProbes.indexOf(this);
  41870. if (index !== -1) {
  41871. // Remove from the scene if found
  41872. this._scene.reflectionProbes.splice(index, 1);
  41873. }
  41874. if (this._renderTargetTexture) {
  41875. this._renderTargetTexture.dispose();
  41876. this._renderTargetTexture = null;
  41877. }
  41878. };
  41879. return ReflectionProbe;
  41880. })();
  41881. BABYLON.ReflectionProbe = ReflectionProbe;
  41882. })(BABYLON || (BABYLON = {}));
  41883. var BABYLON;
  41884. (function (BABYLON) {
  41885. var SolidParticle = (function () {
  41886. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  41887. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  41888. this.position = BABYLON.Vector3.Zero(); // position
  41889. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41890. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  41891. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  41892. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41893. this.alive = true; // alive
  41894. this.idx = particleIndex;
  41895. this._pos = positionIndex;
  41896. this._model = model;
  41897. this.shapeId = shapeId;
  41898. this.idxInShape = idxInShape;
  41899. }
  41900. Object.defineProperty(SolidParticle.prototype, "scale", {
  41901. //legacy support, changed scale to scaling
  41902. get: function () {
  41903. return this.scaling;
  41904. },
  41905. set: function (scale) {
  41906. this.scaling = scale;
  41907. },
  41908. enumerable: true,
  41909. configurable: true
  41910. });
  41911. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41912. //legacy support, changed quaternion to rotationQuaternion
  41913. get: function () {
  41914. return this.rotationQuaternion;
  41915. },
  41916. set: function (q) {
  41917. this.rotationQuaternion = q;
  41918. },
  41919. enumerable: true,
  41920. configurable: true
  41921. });
  41922. return SolidParticle;
  41923. })();
  41924. BABYLON.SolidParticle = SolidParticle;
  41925. var ModelShape = (function () {
  41926. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41927. this.shapeID = id;
  41928. this._shape = shape;
  41929. this._shapeUV = shapeUV;
  41930. this._positionFunction = posFunction;
  41931. this._vertexFunction = vtxFunction;
  41932. }
  41933. return ModelShape;
  41934. })();
  41935. BABYLON.ModelShape = ModelShape;
  41936. })(BABYLON || (BABYLON = {}));
  41937. var BABYLON;
  41938. (function (BABYLON) {
  41939. /**
  41940. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  41941. */
  41942. var SolidParticleSystem = (function () {
  41943. /**
  41944. * Creates a SPS (Solid Particle System) object.
  41945. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41946. * `scene` (Scene) is the scene in which the SPS is added.
  41947. * `updatableè (default true) : if the SPS must be updatable or immutable.
  41948. * `isPickable` (default false) : if the solid particles must be pickable.
  41949. */
  41950. function SolidParticleSystem(name, scene, options) {
  41951. // public members
  41952. /**
  41953. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41954. * Example : var p = SPS.particles[i];
  41955. */
  41956. this.particles = new Array();
  41957. /**
  41958. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41959. */
  41960. this.nbParticles = 0;
  41961. /**
  41962. * If the particles must ever face the camera (default false). Useful for planar particles.
  41963. */
  41964. this.billboard = false;
  41965. /**
  41966. * This a counter ofr your own usage. It's not set by any SPS functions.
  41967. */
  41968. this.counter = 0;
  41969. /**
  41970. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41971. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  41972. */
  41973. this.vars = {};
  41974. this._positions = new Array();
  41975. this._indices = new Array();
  41976. this._normals = new Array();
  41977. this._colors = new Array();
  41978. this._uvs = new Array();
  41979. this._index = 0; // indices index
  41980. this._updatable = true;
  41981. this._pickable = false;
  41982. this._isVisibilityBoxLocked = false;
  41983. this._alwaysVisible = false;
  41984. this._shapeCounter = 0;
  41985. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  41986. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41987. this._computeParticleColor = true;
  41988. this._computeParticleTexture = true;
  41989. this._computeParticleRotation = true;
  41990. this._computeParticleVertex = false;
  41991. this._computeBoundingBox = false;
  41992. this._cam_axisZ = BABYLON.Vector3.Zero();
  41993. this._cam_axisY = BABYLON.Vector3.Zero();
  41994. this._cam_axisX = BABYLON.Vector3.Zero();
  41995. this._axisX = BABYLON.Axis.X;
  41996. this._axisY = BABYLON.Axis.Y;
  41997. this._axisZ = BABYLON.Axis.Z;
  41998. this._fakeCamPos = BABYLON.Vector3.Zero();
  41999. this._rotMatrix = new BABYLON.Matrix();
  42000. this._invertMatrix = new BABYLON.Matrix();
  42001. this._rotated = BABYLON.Vector3.Zero();
  42002. this._quaternion = new BABYLON.Quaternion();
  42003. this._vertex = BABYLON.Vector3.Zero();
  42004. this._normal = BABYLON.Vector3.Zero();
  42005. this._yaw = 0.0;
  42006. this._pitch = 0.0;
  42007. this._roll = 0.0;
  42008. this._halfroll = 0.0;
  42009. this._halfpitch = 0.0;
  42010. this._halfyaw = 0.0;
  42011. this._sinRoll = 0.0;
  42012. this._cosRoll = 0.0;
  42013. this._sinPitch = 0.0;
  42014. this._cosPitch = 0.0;
  42015. this._sinYaw = 0.0;
  42016. this._cosYaw = 0.0;
  42017. this._w = 0.0;
  42018. this._minimum = BABYLON.Tmp.Vector3[0];
  42019. this._maximum = BABYLON.Tmp.Vector3[1];
  42020. this.name = name;
  42021. this._scene = scene;
  42022. this._camera = scene.activeCamera;
  42023. this._pickable = options ? options.isPickable : false;
  42024. if (options && options.updatable) {
  42025. this._updatable = options.updatable;
  42026. }
  42027. else {
  42028. this._updatable = true;
  42029. }
  42030. if (this._pickable) {
  42031. this.pickedParticles = [];
  42032. }
  42033. }
  42034. /**
  42035. * Builds the SPS underlying mesh. Returns a standard Mesh.
  42036. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  42037. */
  42038. SolidParticleSystem.prototype.buildMesh = function () {
  42039. if (this.nbParticles === 0) {
  42040. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  42041. this.addShape(triangle, 1);
  42042. triangle.dispose();
  42043. }
  42044. this._positions32 = new Float32Array(this._positions);
  42045. this._uvs32 = new Float32Array(this._uvs);
  42046. this._colors32 = new Float32Array(this._colors);
  42047. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  42048. this._normals32 = new Float32Array(this._normals);
  42049. this._fixedNormal32 = new Float32Array(this._normals);
  42050. var vertexData = new BABYLON.VertexData();
  42051. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  42052. vertexData.indices = this._indices;
  42053. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  42054. if (this._uvs32) {
  42055. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  42056. ;
  42057. }
  42058. if (this._colors32) {
  42059. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  42060. }
  42061. var mesh = new BABYLON.Mesh(this.name, this._scene);
  42062. vertexData.applyToMesh(mesh, this._updatable);
  42063. this.mesh = mesh;
  42064. this.mesh.isPickable = this._pickable;
  42065. // free memory
  42066. this._positions = null;
  42067. this._normals = null;
  42068. this._uvs = null;
  42069. this._colors = null;
  42070. if (!this._updatable) {
  42071. this.particles.length = 0;
  42072. }
  42073. return mesh;
  42074. };
  42075. /**
  42076. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  42077. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  42078. * Thus the particles generated from `digest()` have their property `position` set yet.
  42079. * `mesh` (`Mesh`) is the mesh to be digested
  42080. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  42081. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  42082. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  42083. */
  42084. SolidParticleSystem.prototype.digest = function (mesh, options) {
  42085. var size = (options && options.facetNb) || 1;
  42086. var number = (options && options.number);
  42087. var delta = (options && options.delta) || 0;
  42088. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42089. var meshInd = mesh.getIndices();
  42090. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42091. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42092. var f = 0; // facet counter
  42093. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  42094. // compute size from number
  42095. if (number) {
  42096. number = (number > totalFacets) ? totalFacets : number;
  42097. size = Math.round(totalFacets / number);
  42098. delta = 0;
  42099. }
  42100. else {
  42101. size = (size > totalFacets) ? totalFacets : size;
  42102. }
  42103. var facetPos = []; // submesh positions
  42104. var facetInd = []; // submesh indices
  42105. var facetUV = []; // submesh UV
  42106. var facetCol = []; // submesh colors
  42107. var barycenter = BABYLON.Tmp.Vector3[0];
  42108. var rand;
  42109. var sizeO = size;
  42110. while (f < totalFacets) {
  42111. size = sizeO + Math.floor((1 + delta) * Math.random());
  42112. if (f > totalFacets - size) {
  42113. size = totalFacets - f;
  42114. }
  42115. // reset temp arrays
  42116. facetPos.length = 0;
  42117. facetInd.length = 0;
  42118. facetUV.length = 0;
  42119. facetCol.length = 0;
  42120. // iterate over "size" facets
  42121. var fi = 0;
  42122. for (var j = f * 3; j < (f + size) * 3; j++) {
  42123. facetInd.push(fi);
  42124. var i = meshInd[j];
  42125. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  42126. if (meshUV) {
  42127. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  42128. }
  42129. if (meshCol) {
  42130. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  42131. }
  42132. fi++;
  42133. }
  42134. // create a model shape for each single particle
  42135. var idx = this.nbParticles;
  42136. var shape = this._posToShape(facetPos);
  42137. var shapeUV = this._uvsToShapeUV(facetUV);
  42138. // compute the barycenter of the shape
  42139. var v;
  42140. for (v = 0; v < shape.length; v++) {
  42141. barycenter.addInPlace(shape[v]);
  42142. }
  42143. barycenter.scaleInPlace(1 / shape.length);
  42144. // shift the shape from its barycenter to the origin
  42145. for (v = 0; v < shape.length; v++) {
  42146. shape[v].subtractInPlace(barycenter);
  42147. }
  42148. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  42149. // add the particle in the SPS
  42150. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  42151. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  42152. // initialize the particle position
  42153. this.particles[this.nbParticles].position.addInPlace(barycenter);
  42154. this._index += shape.length;
  42155. idx++;
  42156. this.nbParticles++;
  42157. this._shapeCounter++;
  42158. f += size;
  42159. }
  42160. return this;
  42161. };
  42162. //reset copy
  42163. SolidParticleSystem.prototype._resetCopy = function () {
  42164. this._copy.position.x = 0;
  42165. this._copy.position.y = 0;
  42166. this._copy.position.z = 0;
  42167. this._copy.rotation.x = 0;
  42168. this._copy.rotation.y = 0;
  42169. this._copy.rotation.z = 0;
  42170. this._copy.rotationQuaternion = null;
  42171. this._copy.scaling.x = 1;
  42172. this._copy.scaling.y = 1;
  42173. this._copy.scaling.z = 1;
  42174. this._copy.uvs.x = 0;
  42175. this._copy.uvs.y = 0;
  42176. this._copy.uvs.z = 1;
  42177. this._copy.uvs.w = 1;
  42178. this._copy.color = null;
  42179. };
  42180. // _meshBuilder : inserts the shape model in the global SPS mesh
  42181. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  42182. var i;
  42183. var u = 0;
  42184. var c = 0;
  42185. this._resetCopy();
  42186. if (options && options.positionFunction) {
  42187. options.positionFunction(this._copy, idx, idxInShape);
  42188. }
  42189. if (this._copy.rotationQuaternion) {
  42190. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42191. }
  42192. else {
  42193. this._yaw = this._copy.rotation.y;
  42194. this._pitch = this._copy.rotation.x;
  42195. this._roll = this._copy.rotation.z;
  42196. this._quaternionRotationYPR();
  42197. }
  42198. this._quaternionToRotationMatrix();
  42199. for (i = 0; i < shape.length; i++) {
  42200. this._vertex.x = shape[i].x;
  42201. this._vertex.y = shape[i].y;
  42202. this._vertex.z = shape[i].z;
  42203. if (options && options.vertexFunction) {
  42204. options.vertexFunction(this._copy, this._vertex, i);
  42205. }
  42206. this._vertex.x *= this._copy.scaling.x;
  42207. this._vertex.y *= this._copy.scaling.y;
  42208. this._vertex.z *= this._copy.scaling.z;
  42209. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42210. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  42211. if (meshUV) {
  42212. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  42213. u += 2;
  42214. }
  42215. if (this._copy.color) {
  42216. this._color = this._copy.color;
  42217. }
  42218. else if (meshCol && meshCol[c]) {
  42219. this._color.r = meshCol[c];
  42220. this._color.g = meshCol[c + 1];
  42221. this._color.b = meshCol[c + 2];
  42222. this._color.a = meshCol[c + 3];
  42223. }
  42224. else {
  42225. this._color.r = 1;
  42226. this._color.g = 1;
  42227. this._color.b = 1;
  42228. this._color.a = 1;
  42229. }
  42230. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  42231. c += 4;
  42232. }
  42233. for (i = 0; i < meshInd.length; i++) {
  42234. indices.push(p + meshInd[i]);
  42235. }
  42236. if (this._pickable) {
  42237. var nbfaces = meshInd.length / 3;
  42238. for (i = 0; i < nbfaces; i++) {
  42239. this.pickedParticles.push({ idx: idx, faceId: i });
  42240. }
  42241. }
  42242. };
  42243. // returns a shape array from positions array
  42244. SolidParticleSystem.prototype._posToShape = function (positions) {
  42245. var shape = [];
  42246. for (var i = 0; i < positions.length; i += 3) {
  42247. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  42248. }
  42249. return shape;
  42250. };
  42251. // returns a shapeUV array from a Vector4 uvs
  42252. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  42253. var shapeUV = [];
  42254. if (uvs) {
  42255. for (var i = 0; i < uvs.length; i++)
  42256. shapeUV.push(uvs[i]);
  42257. }
  42258. return shapeUV;
  42259. };
  42260. // adds a new particle object in the particles array
  42261. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  42262. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  42263. };
  42264. /**
  42265. * Adds some particles to the SPS from the model shape. Returns the shape id.
  42266. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  42267. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  42268. * `nb` (positive integer) the number of particles to be created from this model
  42269. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  42270. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  42271. */
  42272. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  42273. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42274. var meshInd = mesh.getIndices();
  42275. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42276. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42277. var shape = this._posToShape(meshPos);
  42278. var shapeUV = this._uvsToShapeUV(meshUV);
  42279. var posfunc = options ? options.positionFunction : null;
  42280. var vtxfunc = options ? options.vertexFunction : null;
  42281. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  42282. // particles
  42283. var idx = this.nbParticles;
  42284. for (var i = 0; i < nb; i++) {
  42285. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  42286. if (this._updatable) {
  42287. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  42288. }
  42289. this._index += shape.length;
  42290. idx++;
  42291. }
  42292. this.nbParticles += nb;
  42293. this._shapeCounter++;
  42294. return this._shapeCounter - 1;
  42295. };
  42296. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  42297. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  42298. this._resetCopy();
  42299. if (particle._model._positionFunction) {
  42300. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  42301. }
  42302. if (this._copy.rotationQuaternion) {
  42303. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42304. }
  42305. else {
  42306. this._yaw = this._copy.rotation.y;
  42307. this._pitch = this._copy.rotation.x;
  42308. this._roll = this._copy.rotation.z;
  42309. this._quaternionRotationYPR();
  42310. }
  42311. this._quaternionToRotationMatrix();
  42312. this._shape = particle._model._shape;
  42313. for (var pt = 0; pt < this._shape.length; pt++) {
  42314. this._vertex.x = this._shape[pt].x;
  42315. this._vertex.y = this._shape[pt].y;
  42316. this._vertex.z = this._shape[pt].z;
  42317. if (particle._model._vertexFunction) {
  42318. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  42319. }
  42320. this._vertex.x *= this._copy.scaling.x;
  42321. this._vertex.y *= this._copy.scaling.y;
  42322. this._vertex.z *= this._copy.scaling.z;
  42323. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42324. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  42325. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  42326. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  42327. }
  42328. particle.position.x = 0;
  42329. particle.position.y = 0;
  42330. particle.position.z = 0;
  42331. particle.rotation.x = 0;
  42332. particle.rotation.y = 0;
  42333. particle.rotation.z = 0;
  42334. particle.rotationQuaternion = null;
  42335. particle.scaling.x = 1;
  42336. particle.scaling.y = 1;
  42337. particle.scaling.z = 1;
  42338. };
  42339. /**
  42340. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  42341. */
  42342. SolidParticleSystem.prototype.rebuildMesh = function () {
  42343. for (var p = 0; p < this.particles.length; p++) {
  42344. this._rebuildParticle(this.particles[p]);
  42345. }
  42346. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42347. };
  42348. /**
  42349. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  42350. * This method calls `updateParticle()` for each particle of the SPS.
  42351. * For an animated SPS, it is usually called within the render loop.
  42352. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  42353. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  42354. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  42355. */
  42356. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  42357. if (start === void 0) { start = 0; }
  42358. if (end === void 0) { end = this.nbParticles - 1; }
  42359. if (update === void 0) { update = true; }
  42360. if (!this._updatable) {
  42361. return;
  42362. }
  42363. // custom beforeUpdate
  42364. this.beforeUpdateParticles(start, end, update);
  42365. this._cam_axisX.x = 1;
  42366. this._cam_axisX.y = 0;
  42367. this._cam_axisX.z = 0;
  42368. this._cam_axisY.x = 0;
  42369. this._cam_axisY.y = 1;
  42370. this._cam_axisY.z = 0;
  42371. this._cam_axisZ.x = 0;
  42372. this._cam_axisZ.y = 0;
  42373. this._cam_axisZ.z = 1;
  42374. // if the particles will always face the camera
  42375. if (this.billboard) {
  42376. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  42377. this._yaw = this.mesh.rotation.y;
  42378. this._pitch = this.mesh.rotation.x;
  42379. this._roll = this.mesh.rotation.z;
  42380. this._quaternionRotationYPR();
  42381. this._quaternionToRotationMatrix();
  42382. this._rotMatrix.invertToRef(this._invertMatrix);
  42383. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  42384. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  42385. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  42386. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  42387. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  42388. this._cam_axisY.normalize();
  42389. this._cam_axisX.normalize();
  42390. this._cam_axisZ.normalize();
  42391. }
  42392. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  42393. var idx = 0;
  42394. var index = 0;
  42395. var colidx = 0;
  42396. var colorIndex = 0;
  42397. var uvidx = 0;
  42398. var uvIndex = 0;
  42399. if (this._computeBoundingBox) {
  42400. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  42401. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  42402. }
  42403. // particle loop
  42404. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  42405. for (var p = start; p <= end; p++) {
  42406. this._particle = this.particles[p];
  42407. this._shape = this._particle._model._shape;
  42408. this._shapeUV = this._particle._model._shapeUV;
  42409. // call to custom user function to update the particle properties
  42410. this.updateParticle(this._particle);
  42411. // particle rotation matrix
  42412. if (this.billboard) {
  42413. this._particle.rotation.x = 0.0;
  42414. this._particle.rotation.y = 0.0;
  42415. }
  42416. if (this._computeParticleRotation) {
  42417. if (this._particle.rotationQuaternion) {
  42418. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  42419. }
  42420. else {
  42421. this._yaw = this._particle.rotation.y;
  42422. this._pitch = this._particle.rotation.x;
  42423. this._roll = this._particle.rotation.z;
  42424. this._quaternionRotationYPR();
  42425. }
  42426. this._quaternionToRotationMatrix();
  42427. }
  42428. for (var pt = 0; pt < this._shape.length; pt++) {
  42429. idx = index + pt * 3;
  42430. colidx = colorIndex + pt * 4;
  42431. uvidx = uvIndex + pt * 2;
  42432. this._vertex.x = this._shape[pt].x;
  42433. this._vertex.y = this._shape[pt].y;
  42434. this._vertex.z = this._shape[pt].z;
  42435. if (this._computeParticleVertex) {
  42436. this.updateParticleVertex(this._particle, this._vertex, pt);
  42437. }
  42438. // positions
  42439. this._vertex.x *= this._particle.scaling.x;
  42440. this._vertex.y *= this._particle.scaling.y;
  42441. this._vertex.z *= this._particle.scaling.z;
  42442. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  42443. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  42444. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  42445. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  42446. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42447. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  42448. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  42449. if (this._computeBoundingBox) {
  42450. if (this._positions32[idx] < this._minimum.x) {
  42451. this._minimum.x = this._positions32[idx];
  42452. }
  42453. if (this._positions32[idx] > this._maximum.x) {
  42454. this._maximum.x = this._positions32[idx];
  42455. }
  42456. if (this._positions32[idx + 1] < this._minimum.y) {
  42457. this._minimum.y = this._positions32[idx + 1];
  42458. }
  42459. if (this._positions32[idx + 1] > this._maximum.y) {
  42460. this._maximum.y = this._positions32[idx + 1];
  42461. }
  42462. if (this._positions32[idx + 2] < this._minimum.z) {
  42463. this._minimum.z = this._positions32[idx + 2];
  42464. }
  42465. if (this._positions32[idx + 2] > this._maximum.z) {
  42466. this._maximum.z = this._positions32[idx + 2];
  42467. }
  42468. }
  42469. // normals : if the particles can't be morphed then just rotate the normals
  42470. if (!this._computeParticleVertex && !this.billboard) {
  42471. this._normal.x = this._fixedNormal32[idx];
  42472. this._normal.y = this._fixedNormal32[idx + 1];
  42473. this._normal.z = this._fixedNormal32[idx + 2];
  42474. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  42475. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  42476. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  42477. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  42478. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42479. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  42480. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  42481. }
  42482. if (this._computeParticleColor) {
  42483. this._colors32[colidx] = this._particle.color.r;
  42484. this._colors32[colidx + 1] = this._particle.color.g;
  42485. this._colors32[colidx + 2] = this._particle.color.b;
  42486. this._colors32[colidx + 3] = this._particle.color.a;
  42487. }
  42488. if (this._computeParticleTexture) {
  42489. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42490. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42491. }
  42492. }
  42493. index = idx + 3;
  42494. colorIndex = colidx + 4;
  42495. uvIndex = uvidx + 2;
  42496. }
  42497. if (update) {
  42498. if (this._computeParticleColor) {
  42499. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  42500. }
  42501. if (this._computeParticleTexture) {
  42502. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  42503. }
  42504. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42505. if (!this.mesh.areNormalsFrozen) {
  42506. if (this._computeParticleVertex || this.billboard) {
  42507. // recompute the normals only if the particles can be morphed, update then the normal reference array
  42508. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  42509. for (var i = 0; i < this._normals32.length; i++) {
  42510. this._fixedNormal32[i] = this._normals32[i];
  42511. }
  42512. }
  42513. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  42514. }
  42515. }
  42516. if (this._computeBoundingBox) {
  42517. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  42518. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  42519. }
  42520. this.afterUpdateParticles(start, end, update);
  42521. };
  42522. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42523. this._halfroll = this._roll * 0.5;
  42524. this._halfpitch = this._pitch * 0.5;
  42525. this._halfyaw = this._yaw * 0.5;
  42526. this._sinRoll = Math.sin(this._halfroll);
  42527. this._cosRoll = Math.cos(this._halfroll);
  42528. this._sinPitch = Math.sin(this._halfpitch);
  42529. this._cosPitch = Math.cos(this._halfpitch);
  42530. this._sinYaw = Math.sin(this._halfyaw);
  42531. this._cosYaw = Math.cos(this._halfyaw);
  42532. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  42533. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  42534. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  42535. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  42536. };
  42537. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42538. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42539. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42540. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42541. this._rotMatrix.m[3] = 0;
  42542. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42543. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42544. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42545. this._rotMatrix.m[7] = 0;
  42546. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42547. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42548. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42549. this._rotMatrix.m[11] = 0;
  42550. this._rotMatrix.m[12] = 0;
  42551. this._rotMatrix.m[13] = 0;
  42552. this._rotMatrix.m[14] = 0;
  42553. this._rotMatrix.m[15] = 1.0;
  42554. };
  42555. /**
  42556. * Disposes the SPS
  42557. */
  42558. SolidParticleSystem.prototype.dispose = function () {
  42559. this.mesh.dispose();
  42560. this.vars = null;
  42561. // drop references to internal big arrays for the GC
  42562. this._positions = null;
  42563. this._indices = null;
  42564. this._normals = null;
  42565. this._uvs = null;
  42566. this._colors = null;
  42567. this._positions32 = null;
  42568. this._normals32 = null;
  42569. this._fixedNormal32 = null;
  42570. this._uvs32 = null;
  42571. this._colors32 = null;
  42572. this.pickedParticles = null;
  42573. };
  42574. /**
  42575. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42576. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42577. */
  42578. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42579. if (!this._isVisibilityBoxLocked) {
  42580. this.mesh.refreshBoundingInfo();
  42581. }
  42582. };
  42583. /**
  42584. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42585. * @param size the size (float) of the visibility box
  42586. * note : this doesn't lock the SPS mesh bounding box.
  42587. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42588. */
  42589. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42590. var vis = size / 2;
  42591. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42592. };
  42593. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42594. // getter and setter
  42595. get: function () {
  42596. return this._alwaysVisible;
  42597. },
  42598. /**
  42599. * Sets the SPS as always visible or not
  42600. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42601. */
  42602. set: function (val) {
  42603. this._alwaysVisible = val;
  42604. this.mesh.alwaysSelectAsActiveMesh = val;
  42605. },
  42606. enumerable: true,
  42607. configurable: true
  42608. });
  42609. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42610. get: function () {
  42611. return this._isVisibilityBoxLocked;
  42612. },
  42613. /**
  42614. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42615. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42616. */
  42617. set: function (val) {
  42618. this._isVisibilityBoxLocked = val;
  42619. this.mesh.getBoundingInfo().isLocked = val;
  42620. },
  42621. enumerable: true,
  42622. configurable: true
  42623. });
  42624. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42625. // getters
  42626. get: function () {
  42627. return this._computeParticleRotation;
  42628. },
  42629. // Optimizer setters
  42630. /**
  42631. * Tells to `setParticles()` to compute the particle rotations or not.
  42632. * Default value : true. The SPS is faster when it's set to false.
  42633. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42634. */
  42635. set: function (val) {
  42636. this._computeParticleRotation = val;
  42637. },
  42638. enumerable: true,
  42639. configurable: true
  42640. });
  42641. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42642. get: function () {
  42643. return this._computeParticleColor;
  42644. },
  42645. /**
  42646. * Tells to `setParticles()` to compute the particle colors or not.
  42647. * Default value : true. The SPS is faster when it's set to false.
  42648. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42649. */
  42650. set: function (val) {
  42651. this._computeParticleColor = val;
  42652. },
  42653. enumerable: true,
  42654. configurable: true
  42655. });
  42656. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42657. get: function () {
  42658. return this._computeParticleTexture;
  42659. },
  42660. /**
  42661. * Tells to `setParticles()` to compute the particle textures or not.
  42662. * Default value : true. The SPS is faster when it's set to false.
  42663. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42664. */
  42665. set: function (val) {
  42666. this._computeParticleTexture = val;
  42667. },
  42668. enumerable: true,
  42669. configurable: true
  42670. });
  42671. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42672. get: function () {
  42673. return this._computeParticleVertex;
  42674. },
  42675. /**
  42676. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42677. * Default value : false. The SPS is faster when it's set to false.
  42678. * Note : the particle custom vertex positions aren't stored values.
  42679. */
  42680. set: function (val) {
  42681. this._computeParticleVertex = val;
  42682. },
  42683. enumerable: true,
  42684. configurable: true
  42685. });
  42686. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42687. get: function () {
  42688. return this._computeBoundingBox;
  42689. },
  42690. /**
  42691. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42692. */
  42693. set: function (val) {
  42694. this._computeBoundingBox = val;
  42695. },
  42696. enumerable: true,
  42697. configurable: true
  42698. });
  42699. // =======================================================================
  42700. // Particle behavior logic
  42701. // these following methods may be overwritten by the user to fit his needs
  42702. /**
  42703. * This function does nothing. It may be overwritten to set all the particle first values.
  42704. * The SPS doesn't call this function, you may have to call it by your own.
  42705. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42706. */
  42707. SolidParticleSystem.prototype.initParticles = function () {
  42708. };
  42709. /**
  42710. * This function does nothing. It may be overwritten to recycle a particle.
  42711. * The SPS doesn't call this function, you may have to call it by your own.
  42712. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42713. */
  42714. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42715. return particle;
  42716. };
  42717. /**
  42718. * Updates a particle : this function should be overwritten by the user.
  42719. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42720. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42721. * ex : just set a particle position or velocity and recycle conditions
  42722. */
  42723. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42724. return particle;
  42725. };
  42726. /**
  42727. * Updates a vertex of a particle : it can be overwritten by the user.
  42728. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42729. * @param particle the current particle
  42730. * @param vertex the current index of the current particle
  42731. * @param pt the index of the current vertex in the particle shape
  42732. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  42733. * ex : just set a vertex particle position
  42734. */
  42735. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42736. return vertex;
  42737. };
  42738. /**
  42739. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42740. * This does nothing and may be overwritten by the user.
  42741. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42742. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42743. * @param update the boolean update value actually passed to setParticles()
  42744. */
  42745. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42746. };
  42747. /**
  42748. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42749. * This will be passed three parameters.
  42750. * This does nothing and may be overwritten by the user.
  42751. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42752. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42753. * @param update the boolean update value actually passed to setParticles()
  42754. */
  42755. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42756. };
  42757. return SolidParticleSystem;
  42758. })();
  42759. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42760. })(BABYLON || (BABYLON = {}));
  42761. var BABYLON;
  42762. (function (BABYLON) {
  42763. var Internals;
  42764. (function (Internals) {
  42765. var FileFaceOrientation = (function () {
  42766. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42767. this.name = name;
  42768. this.worldAxisForNormal = worldAxisForNormal;
  42769. this.worldAxisForFileX = worldAxisForFileX;
  42770. this.worldAxisForFileY = worldAxisForFileY;
  42771. }
  42772. return FileFaceOrientation;
  42773. })();
  42774. ;
  42775. /**
  42776. * Helper class dealing with the extraction of spherical polynomial dataArray
  42777. * from a cube map.
  42778. */
  42779. var CubeMapToSphericalPolynomialTools = (function () {
  42780. function CubeMapToSphericalPolynomialTools() {
  42781. }
  42782. /**
  42783. * Converts a cubemap to the according Spherical Polynomial data.
  42784. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42785. *
  42786. * @param cubeInfo The Cube map to extract the information from.
  42787. * @return The Spherical Polynomial data.
  42788. */
  42789. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42790. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42791. var totalSolidAngle = 0.0;
  42792. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42793. var du = 2.0 / cubeInfo.size;
  42794. var dv = du;
  42795. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42796. var minUV = du * 0.5 - 1.0;
  42797. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42798. var fileFace = this.FileFaces[faceIndex];
  42799. var dataArray = cubeInfo[fileFace.name];
  42800. var v = minUV;
  42801. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42802. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42803. // Because SP is still linear, so summation is fine in that basis.
  42804. for (var y = 0; y < cubeInfo.size; y++) {
  42805. var u = minUV;
  42806. for (var x = 0; x < cubeInfo.size; x++) {
  42807. // World direction (not normalised)
  42808. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  42809. worldDirection.normalize();
  42810. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  42811. if (1) {
  42812. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  42813. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  42814. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  42815. var color = new BABYLON.Color3(r, g, b);
  42816. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42817. }
  42818. else {
  42819. if (faceIndex == 0) {
  42820. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42821. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42822. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42823. }
  42824. else if (faceIndex == 1) {
  42825. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42826. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42827. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42828. }
  42829. else if (faceIndex == 2) {
  42830. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42831. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42832. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42833. }
  42834. else if (faceIndex == 3) {
  42835. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42836. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42837. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42838. }
  42839. else if (faceIndex == 4) {
  42840. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42841. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42842. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42843. }
  42844. else if (faceIndex == 5) {
  42845. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42846. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42847. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42848. }
  42849. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  42850. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42851. }
  42852. totalSolidAngle += deltaSolidAngle;
  42853. u += du;
  42854. }
  42855. v += dv;
  42856. }
  42857. }
  42858. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  42859. var correction = correctSolidAngle / totalSolidAngle;
  42860. sphericalHarmonics.scale(correction);
  42861. // Additionally scale by pi -- audit needed
  42862. sphericalHarmonics.scale(1.0 / Math.PI);
  42863. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  42864. };
  42865. CubeMapToSphericalPolynomialTools.FileFaces = [
  42866. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  42867. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  42868. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  42869. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  42870. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  42871. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  42872. ];
  42873. return CubeMapToSphericalPolynomialTools;
  42874. })();
  42875. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  42876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42877. })(BABYLON || (BABYLON = {}));
  42878. var BABYLON;
  42879. (function (BABYLON) {
  42880. var Internals;
  42881. (function (Internals) {
  42882. /**
  42883. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  42884. */
  42885. var PanoramaToCubeMapTools = (function () {
  42886. function PanoramaToCubeMapTools() {
  42887. }
  42888. /**
  42889. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  42890. *
  42891. * @param float32Array The source data.
  42892. * @param inputWidth The width of the input panorama.
  42893. * @param inputhHeight The height of the input panorama.
  42894. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  42895. * @return The cubemap data
  42896. */
  42897. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  42898. if (!float32Array) {
  42899. throw "ConvertPanoramaToCubemap: input cannot be null";
  42900. }
  42901. if (float32Array.length != inputWidth * inputHeight * 3) {
  42902. throw "ConvertPanoramaToCubemap: input size is wrong";
  42903. }
  42904. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  42905. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  42906. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  42907. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  42908. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  42909. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  42910. return {
  42911. front: textureFront,
  42912. back: textureBack,
  42913. left: textureLeft,
  42914. right: textureRight,
  42915. up: textureUp,
  42916. down: textureDown,
  42917. size: size
  42918. };
  42919. };
  42920. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  42921. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  42922. var textureArray = new Float32Array(buffer);
  42923. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  42924. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  42925. var dy = 1 / texSize;
  42926. var fy = 0;
  42927. for (var y = 0; y < texSize; y++) {
  42928. var xv1 = faceData[0];
  42929. var xv2 = faceData[2];
  42930. for (var x = 0; x < texSize; x++) {
  42931. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  42932. v.normalize();
  42933. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  42934. // 3 channels per pixels
  42935. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  42936. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  42937. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  42938. xv1 = xv1.add(rotDX1);
  42939. xv2 = xv2.add(rotDX2);
  42940. }
  42941. fy += dy;
  42942. }
  42943. return textureArray;
  42944. };
  42945. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  42946. var theta = Math.atan2(vDir.z, vDir.x);
  42947. var phi = Math.acos(vDir.y);
  42948. while (theta < -Math.PI)
  42949. theta += 2 * Math.PI;
  42950. while (theta > Math.PI)
  42951. theta -= 2 * Math.PI;
  42952. var dx = theta / Math.PI;
  42953. var dy = phi / Math.PI;
  42954. // recenter.
  42955. dx = dx * 0.5 + 0.5;
  42956. var px = Math.round(dx * inputWidth);
  42957. if (px < 0)
  42958. px = 0;
  42959. else if (px >= inputWidth)
  42960. px = inputWidth - 1;
  42961. var py = Math.round(dy * inputHeight);
  42962. if (py < 0)
  42963. py = 0;
  42964. else if (py >= inputHeight)
  42965. py = inputHeight - 1;
  42966. var inputY = (inputHeight - py - 1);
  42967. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  42968. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  42969. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  42970. return {
  42971. r: r,
  42972. g: g,
  42973. b: b
  42974. };
  42975. };
  42976. PanoramaToCubeMapTools.FACE_FRONT = [
  42977. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42978. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42979. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42980. new BABYLON.Vector3(1.0, 1.0, -1.0)
  42981. ];
  42982. PanoramaToCubeMapTools.FACE_BACK = [
  42983. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42984. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42985. new BABYLON.Vector3(1.0, 1.0, 1.0),
  42986. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  42987. ];
  42988. PanoramaToCubeMapTools.FACE_RIGHT = [
  42989. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42990. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42991. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42992. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42993. ];
  42994. PanoramaToCubeMapTools.FACE_LEFT = [
  42995. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42996. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42997. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42998. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  42999. ];
  43000. PanoramaToCubeMapTools.FACE_DOWN = [
  43001. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  43002. new BABYLON.Vector3(1.0, 1.0, -1.0),
  43003. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  43004. new BABYLON.Vector3(1.0, 1.0, 1.0)
  43005. ];
  43006. PanoramaToCubeMapTools.FACE_UP = [
  43007. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  43008. new BABYLON.Vector3(1.0, -1.0, 1.0),
  43009. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  43010. new BABYLON.Vector3(1.0, -1.0, -1.0)
  43011. ];
  43012. return PanoramaToCubeMapTools;
  43013. })();
  43014. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  43015. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43016. })(BABYLON || (BABYLON = {}));
  43017. var BABYLON;
  43018. (function (BABYLON) {
  43019. var Internals;
  43020. (function (Internals) {
  43021. ;
  43022. /**
  43023. * This groups tools to convert HDR texture to native colors array.
  43024. */
  43025. var HDRTools = (function () {
  43026. function HDRTools() {
  43027. }
  43028. HDRTools.Ldexp = function (mantissa, exponent) {
  43029. if (exponent > 1023) {
  43030. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  43031. }
  43032. if (exponent < -1074) {
  43033. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  43034. }
  43035. return mantissa * Math.pow(2, exponent);
  43036. };
  43037. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  43038. if (exponent > 0) {
  43039. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  43040. float32array[index + 0] = red * exponent;
  43041. float32array[index + 1] = green * exponent;
  43042. float32array[index + 2] = blue * exponent;
  43043. }
  43044. else {
  43045. float32array[index + 0] = 0;
  43046. float32array[index + 1] = 0;
  43047. float32array[index + 2] = 0;
  43048. }
  43049. };
  43050. HDRTools.readStringLine = function (uint8array, startIndex) {
  43051. var line = "";
  43052. var character = "";
  43053. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  43054. character = String.fromCharCode(uint8array[i]);
  43055. if (character == "\n") {
  43056. break;
  43057. }
  43058. line += character;
  43059. }
  43060. return line;
  43061. };
  43062. /**
  43063. * Reads header information from an RGBE texture stored in a native array.
  43064. * More information on this format are available here:
  43065. * https://en.wikipedia.org/wiki/RGBE_image_format
  43066. *
  43067. * @param uint8array The binary file stored in native array.
  43068. * @return The header information.
  43069. */
  43070. HDRTools.RGBE_ReadHeader = function (uint8array) {
  43071. var height = 0;
  43072. var width = 0;
  43073. var line = this.readStringLine(uint8array, 0);
  43074. if (line[0] != '#' || line[1] != '?') {
  43075. throw "Bad HDR Format.";
  43076. }
  43077. var endOfHeader = false;
  43078. var findFormat = false;
  43079. var lineIndex = 0;
  43080. do {
  43081. lineIndex += (line.length + 1);
  43082. line = this.readStringLine(uint8array, lineIndex);
  43083. if (line == "FORMAT=32-bit_rle_rgbe") {
  43084. findFormat = true;
  43085. }
  43086. else if (line.length == 0) {
  43087. endOfHeader = true;
  43088. }
  43089. } while (!endOfHeader);
  43090. if (!findFormat) {
  43091. throw "HDR Bad header format, unsupported FORMAT";
  43092. }
  43093. lineIndex += (line.length + 1);
  43094. line = this.readStringLine(uint8array, lineIndex);
  43095. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  43096. var match = sizeRegexp.exec(line);
  43097. // TODO. Support +Y and -X if needed.
  43098. if (match.length < 3) {
  43099. throw "HDR Bad header format, no size";
  43100. }
  43101. width = parseInt(match[2]);
  43102. height = parseInt(match[1]);
  43103. if (width < 8 || width > 0x7fff) {
  43104. throw "HDR Bad header format, unsupported size";
  43105. }
  43106. lineIndex += (line.length + 1);
  43107. return {
  43108. height: height,
  43109. width: width,
  43110. dataPosition: lineIndex
  43111. };
  43112. };
  43113. /**
  43114. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  43115. * This RGBE texture needs to store the information as a panorama.
  43116. *
  43117. * More information on this format are available here:
  43118. * https://en.wikipedia.org/wiki/RGBE_image_format
  43119. *
  43120. * @param buffer The binary file stored in an array buffer.
  43121. * @param size The expected size of the extracted cubemap.
  43122. * @return The Cube Map information.
  43123. */
  43124. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  43125. var uint8array = new Uint8Array(buffer);
  43126. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  43127. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  43128. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  43129. return cubeMapData;
  43130. };
  43131. /**
  43132. * Returns the pixels data extracted from an RGBE texture.
  43133. * This pixels will be stored left to right up to down in the R G B order in one array.
  43134. *
  43135. * More information on this format are available here:
  43136. * https://en.wikipedia.org/wiki/RGBE_image_format
  43137. *
  43138. * @param uint8array The binary file stored in an array buffer.
  43139. * @param hdrInfo The header information of the file.
  43140. * @return The pixels data in RGB right to left up to down order.
  43141. */
  43142. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  43143. // Keep for multi format supports.
  43144. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  43145. };
  43146. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  43147. var num_scanlines = hdrInfo.height;
  43148. var scanline_width = hdrInfo.width;
  43149. var a, b, c, d, count;
  43150. var dataIndex = hdrInfo.dataPosition;
  43151. var index = 0, endIndex = 0, i = 0;
  43152. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  43153. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  43154. // 3 channels of 4 bytes per pixel in float.
  43155. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  43156. var resultArray = new Float32Array(resultBuffer);
  43157. // read in each successive scanline
  43158. while (num_scanlines > 0) {
  43159. a = uint8array[dataIndex++];
  43160. b = uint8array[dataIndex++];
  43161. c = uint8array[dataIndex++];
  43162. d = uint8array[dataIndex++];
  43163. if (a != 2 || b != 2 || (c & 0x80)) {
  43164. // this file is not run length encoded
  43165. throw "HDR Bad header format, not RLE";
  43166. }
  43167. if (((c << 8) | d) != scanline_width) {
  43168. throw "HDR Bad header format, wrong scan line width";
  43169. }
  43170. index = 0;
  43171. // read each of the four channels for the scanline into the buffer
  43172. for (i = 0; i < 4; i++) {
  43173. endIndex = (i + 1) * scanline_width;
  43174. while (index < endIndex) {
  43175. a = uint8array[dataIndex++];
  43176. b = uint8array[dataIndex++];
  43177. if (a > 128) {
  43178. // a run of the same value
  43179. count = a - 128;
  43180. if ((count == 0) || (count > endIndex - index)) {
  43181. throw "HDR Bad Format, bad scanline data (run)";
  43182. }
  43183. while (count-- > 0) {
  43184. scanLineArray[index++] = b;
  43185. }
  43186. }
  43187. else {
  43188. // a non-run
  43189. count = a;
  43190. if ((count == 0) || (count > endIndex - index)) {
  43191. throw "HDR Bad Format, bad scanline data (non-run)";
  43192. }
  43193. scanLineArray[index++] = b;
  43194. if (--count > 0) {
  43195. for (var j = 0; j < count; j++) {
  43196. scanLineArray[index++] = uint8array[dataIndex++];
  43197. }
  43198. }
  43199. }
  43200. }
  43201. }
  43202. // now convert data from buffer into floats
  43203. for (i = 0; i < scanline_width; i++) {
  43204. a = scanLineArray[i];
  43205. b = scanLineArray[i + scanline_width];
  43206. c = scanLineArray[i + 2 * scanline_width];
  43207. d = scanLineArray[i + 3 * scanline_width];
  43208. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  43209. }
  43210. num_scanlines--;
  43211. }
  43212. return resultArray;
  43213. };
  43214. return HDRTools;
  43215. })();
  43216. Internals.HDRTools = HDRTools;
  43217. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43218. })(BABYLON || (BABYLON = {}));
  43219. //_______________________________________________________________
  43220. // Extracted from CubeMapGen:
  43221. // https://code.google.com/archive/p/cubemapgen/
  43222. //
  43223. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  43224. //_______________________________________________________________
  43225. var BABYLON;
  43226. (function (BABYLON) {
  43227. var Internals;
  43228. (function (Internals) {
  43229. /**
  43230. * The bounding box information used during the conversion process.
  43231. */
  43232. var CMGBoundinBox = (function () {
  43233. function CMGBoundinBox() {
  43234. this.min = new BABYLON.Vector3(0, 0, 0);
  43235. this.max = new BABYLON.Vector3(0, 0, 0);
  43236. this.clear();
  43237. }
  43238. CMGBoundinBox.prototype.clear = function () {
  43239. this.min.x = CMGBoundinBox.MAX;
  43240. this.min.y = CMGBoundinBox.MAX;
  43241. this.min.z = CMGBoundinBox.MAX;
  43242. this.max.x = CMGBoundinBox.MIN;
  43243. this.max.y = CMGBoundinBox.MIN;
  43244. this.max.z = CMGBoundinBox.MIN;
  43245. };
  43246. CMGBoundinBox.prototype.augment = function (x, y, z) {
  43247. this.min.x = Math.min(this.min.x, x);
  43248. this.min.y = Math.min(this.min.y, y);
  43249. this.min.z = Math.min(this.min.z, z);
  43250. this.max.x = Math.max(this.max.x, x);
  43251. this.max.y = Math.max(this.max.y, y);
  43252. this.max.z = Math.max(this.max.z, z);
  43253. };
  43254. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  43255. this.min.x = Math.max(this.min.x, x);
  43256. this.min.y = Math.max(this.min.y, y);
  43257. this.min.z = Math.max(this.min.z, z);
  43258. };
  43259. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  43260. this.max.x = Math.min(this.max.x, x);
  43261. this.max.y = Math.min(this.max.y, y);
  43262. this.max.z = Math.min(this.max.z, z);
  43263. };
  43264. CMGBoundinBox.prototype.empty = function () {
  43265. if ((this.min.x > this.max.y) ||
  43266. (this.min.y > this.max.y) ||
  43267. (this.min.z > this.max.y)) {
  43268. return true;
  43269. }
  43270. else {
  43271. return false;
  43272. }
  43273. };
  43274. CMGBoundinBox.MAX = Number.MAX_VALUE;
  43275. CMGBoundinBox.MIN = Number.MIN_VALUE;
  43276. return CMGBoundinBox;
  43277. })();
  43278. /**
  43279. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  43280. * required by the glossinees of a material.
  43281. *
  43282. * This only supports the cosine drop power as well as Warp fixup generation method.
  43283. *
  43284. * This is using the process from CubeMapGen described here:
  43285. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  43286. */
  43287. var PMREMGenerator = (function () {
  43288. /**
  43289. * Constructor of the generator.
  43290. *
  43291. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  43292. * @param inputSize The size of the cubemap faces
  43293. * @param outputSize The size of the output cubemap faces
  43294. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  43295. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  43296. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  43297. * @param specularPower The max specular level of the desired cubemap
  43298. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  43299. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  43300. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  43301. */
  43302. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  43303. this.input = input;
  43304. this.inputSize = inputSize;
  43305. this.outputSize = outputSize;
  43306. this.maxNumMipLevels = maxNumMipLevels;
  43307. this.numChannels = numChannels;
  43308. this.isFloat = isFloat;
  43309. this.specularPower = specularPower;
  43310. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  43311. this.excludeBase = excludeBase;
  43312. this.fixup = fixup;
  43313. this._outputSurface = [];
  43314. this._numMipLevels = 0;
  43315. }
  43316. /**
  43317. * Launches the filter process and return the result.
  43318. *
  43319. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  43320. */
  43321. PMREMGenerator.prototype.filterCubeMap = function () {
  43322. // Init cubemap processor
  43323. this.init();
  43324. // Filters the cubemap
  43325. this.filterCubeMapMipChain();
  43326. // Returns the filtered mips.
  43327. return this._outputSurface;
  43328. };
  43329. PMREMGenerator.prototype.init = function () {
  43330. var i;
  43331. var j;
  43332. var mipLevelSize;
  43333. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  43334. if (this.maxNumMipLevels == 0) {
  43335. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  43336. }
  43337. //first miplevel size
  43338. mipLevelSize = this.outputSize;
  43339. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  43340. for (j = 0; j < this.maxNumMipLevels; j++) {
  43341. this._outputSurface.length++;
  43342. this._outputSurface[j] = [];
  43343. //Iterate over faces for output images
  43344. for (i = 0; i < 6; i++) {
  43345. this._outputSurface[j].length++;
  43346. // Initializes a new array for the output.
  43347. if (this.isFloat) {
  43348. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  43349. }
  43350. else {
  43351. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  43352. }
  43353. }
  43354. //next mip level is half size
  43355. mipLevelSize >>= 1;
  43356. this._numMipLevels++;
  43357. //terminate if mip chain becomes too small
  43358. if (mipLevelSize == 0) {
  43359. this.maxNumMipLevels = j;
  43360. return;
  43361. }
  43362. }
  43363. };
  43364. //--------------------------------------------------------------------------------------
  43365. //Cube map filtering and mip chain generation.
  43366. // the cube map filtereing is specified using a number of parameters:
  43367. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  43368. // indicates the region of the hemisphere to filter over for each tap.
  43369. //
  43370. // Note that the top mip level is also a filtered version of the original input images
  43371. // as well in order to create mip chains for diffuse environment illumination.
  43372. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  43373. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  43374. //
  43375. // Then the mip angle used to genreate the next level of the mip chain from the first level
  43376. // is a_InitialMipAngle
  43377. //
  43378. // The angle for the subsequent levels of the mip chain are specified by their parents
  43379. // filtering angle and a per-level scale and bias
  43380. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  43381. //
  43382. //--------------------------------------------------------------------------------------
  43383. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  43384. // First, take count of the lighting model to modify SpecularPower
  43385. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  43386. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  43387. //Cone angle start (for generating subsequent mip levels)
  43388. var currentSpecularPower = this.specularPower;
  43389. //Build filter lookup tables based on the source miplevel size
  43390. this.precomputeFilterLookupTables(this.inputSize);
  43391. // Note that we need to filter the first level before generating mipmap
  43392. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  43393. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  43394. // TODO : Write a function to copy and scale the base mipmap in output
  43395. // I am just lazy here and just put a high specular power value, and do some if.
  43396. if (this.excludeBase && (levelIndex == 0)) {
  43397. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  43398. currentSpecularPower = 100000.0;
  43399. }
  43400. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  43401. var srcCubeImage = this.input;
  43402. var dstCubeImage = this._outputSurface[levelIndex];
  43403. var dstSize = this.outputSize >> levelIndex;
  43404. // Compute required angle.
  43405. var angle = this.getBaseFilterAngle(currentSpecularPower);
  43406. // filter cube surfaces
  43407. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  43408. // fix seams
  43409. if (this.fixup) {
  43410. this.fixupCubeEdges(dstCubeImage, dstSize);
  43411. }
  43412. // Decrease the specular power to generate the mipmap chain
  43413. // TODO : Use another method for Exclude (see first comment at start of the function
  43414. if (this.excludeBase && (levelIndex == 0)) {
  43415. currentSpecularPower = this.specularPower;
  43416. }
  43417. currentSpecularPower *= this.cosinePowerDropPerMip;
  43418. }
  43419. };
  43420. //--------------------------------------------------------------------------------------
  43421. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  43422. // It allow to optimize the texel to access base on the specular power.
  43423. //--------------------------------------------------------------------------------------
  43424. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  43425. // We want to find the alpha such that:
  43426. // cos(alpha)^cosinePower = epsilon
  43427. // That's: acos(epsilon^(1/cosinePower))
  43428. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  43429. var angle = 180.0;
  43430. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  43431. angle *= 180.0 / Math.PI; // Convert to degree
  43432. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  43433. return angle;
  43434. };
  43435. //--------------------------------------------------------------------------------------
  43436. //Builds the following lookup tables prior to filtering:
  43437. // -normalizer cube map
  43438. // -tap weight lookup table
  43439. //
  43440. //--------------------------------------------------------------------------------------
  43441. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  43442. var srcTexelAngle;
  43443. var iCubeFace;
  43444. //clear pre-existing normalizer cube map
  43445. this._normCubeMap = [];
  43446. //Normalized vectors per cubeface and per-texel solid angle
  43447. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  43448. };
  43449. //--------------------------------------------------------------------------------------
  43450. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  43451. //
  43452. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  43453. //
  43454. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  43455. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  43456. // below
  43457. //--------------------------------------------------------------------------------------
  43458. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  43459. var iCubeFace;
  43460. var u;
  43461. var v;
  43462. //iterate over cube faces
  43463. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43464. //First three channels for norm cube, and last channel for solid angle
  43465. this._normCubeMap.push(new Float32Array(size * size * 4));
  43466. //fast texture walk, build normalizer cube map
  43467. var facesData = this.input[iCubeFace];
  43468. for (v = 0; v < size; v++) {
  43469. for (u = 0; u < size; u++) {
  43470. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  43471. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  43472. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  43473. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  43474. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  43475. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  43476. }
  43477. }
  43478. }
  43479. };
  43480. //--------------------------------------------------------------------------------------
  43481. // Convert cubemap face texel coordinates and face idx to 3D vector
  43482. // note the U and V coords are integer coords and range from 0 to size-1
  43483. // this routine can be used to generate a normalizer cube map
  43484. //--------------------------------------------------------------------------------------
  43485. // SL BEGIN
  43486. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  43487. var nvcU;
  43488. var nvcV;
  43489. var tempVec;
  43490. // Change from original AMD code
  43491. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  43492. // + 0.5f is for texel center addressing
  43493. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  43494. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  43495. // warp fixup
  43496. if (fixup && size > 1) {
  43497. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  43498. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  43499. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  43500. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  43501. }
  43502. // Get current vector
  43503. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  43504. // U contribution
  43505. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  43506. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  43507. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  43508. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  43509. // V contribution and Sum
  43510. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  43511. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  43512. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  43513. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  43514. //add face axis
  43515. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  43516. PMREMGenerator._vectorTemp.x += faceAxis[0];
  43517. PMREMGenerator._vectorTemp.y += faceAxis[1];
  43518. PMREMGenerator._vectorTemp.z += faceAxis[2];
  43519. //normalize vector
  43520. PMREMGenerator._vectorTemp.normalize();
  43521. return PMREMGenerator._vectorTemp;
  43522. };
  43523. //--------------------------------------------------------------------------------------
  43524. // Convert 3D vector to cubemap face texel coordinates and face idx
  43525. // note the U and V coords are integer coords and range from 0 to size-1
  43526. // this routine can be used to generate a normalizer cube map
  43527. //
  43528. // returns face IDX and texel coords
  43529. //--------------------------------------------------------------------------------------
  43530. // SL BEGIN
  43531. /*
  43532. Mapping Texture Coordinates to Cube Map Faces
  43533. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  43534. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  43535. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  43536. map arrangement in Pixar's RenderMan package.
  43537. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  43538. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  43539. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  43540. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  43541. the major axis direction). The target column in the table below explains how the major axis direction
  43542. maps to the 2D image of a particular cube map target.
  43543. major axis
  43544. direction target sc tc ma
  43545. ---------- --------------------------------- --- --- ---
  43546. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  43547. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  43548. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  43549. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  43550. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  43551. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  43552. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  43553. an updated (s,t) is calculated as follows
  43554. s = ( sc/|ma| + 1 ) / 2
  43555. t = ( tc/|ma| + 1 ) / 2
  43556. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  43557. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  43558. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  43559. */
  43560. // Note this method return U and V in range from 0 to size-1
  43561. // SL END
  43562. // Store the information in vector3 for convenience (faceindex, u, v)
  43563. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  43564. var maxCoord;
  43565. var faceIdx;
  43566. //absolute value 3
  43567. var absX = Math.abs(x);
  43568. var absY = Math.abs(y);
  43569. var absZ = Math.abs(z);
  43570. if (absX >= absY && absX >= absZ) {
  43571. maxCoord = absX;
  43572. if (x >= 0) {
  43573. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  43574. }
  43575. else {
  43576. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43577. }
  43578. }
  43579. else if (absY >= absX && absY >= absZ) {
  43580. maxCoord = absY;
  43581. if (y >= 0) {
  43582. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43583. }
  43584. else {
  43585. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43586. }
  43587. }
  43588. else {
  43589. maxCoord = absZ;
  43590. if (z >= 0) {
  43591. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43592. }
  43593. else {
  43594. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43595. }
  43596. }
  43597. //divide through by max coord so face vector lies on cube face
  43598. var scale = 1 / maxCoord;
  43599. x *= scale;
  43600. y *= scale;
  43601. z *= scale;
  43602. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  43603. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  43604. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  43605. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  43606. // Modify original AMD code to return value from 0 to Size - 1
  43607. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  43608. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  43609. PMREMGenerator._vectorTemp.x = faceIdx;
  43610. PMREMGenerator._vectorTemp.y = u;
  43611. PMREMGenerator._vectorTemp.z = v;
  43612. return PMREMGenerator._vectorTemp;
  43613. };
  43614. //--------------------------------------------------------------------------------------
  43615. //Original code from Ignacio CastaÒo
  43616. // This formula is from Manne ÷hrstrˆm's thesis.
  43617. // Take two coordiantes in the range [-1, 1] that define a portion of a
  43618. // cube face and return the area of the projection of that portion on the
  43619. // surface of the sphere.
  43620. //--------------------------------------------------------------------------------------
  43621. PMREMGenerator.prototype.areaElement = function (x, y) {
  43622. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  43623. };
  43624. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  43625. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  43626. // (+ 0.5f is for texel center addressing)
  43627. u = (2.0 * (u + 0.5) / size) - 1.0;
  43628. v = (2.0 * (v + 0.5) / size) - 1.0;
  43629. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  43630. var invResolution = 1.0 / size;
  43631. // U and V are the -1..1 texture coordinate on the current face.
  43632. // Get projected area for this texel
  43633. var x0 = u - invResolution;
  43634. var y0 = v - invResolution;
  43635. var x1 = u + invResolution;
  43636. var y1 = v + invResolution;
  43637. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  43638. return solidAngle;
  43639. };
  43640. //--------------------------------------------------------------------------------------
  43641. //The key to the speed of these filtering routines is to quickly define a per-face
  43642. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  43643. // Later these pixels are selectively processed based on their dot products to see if
  43644. // they reside within the filtering cone.
  43645. //
  43646. //This is done by computing the smallest per-texel angle to get a conservative estimate
  43647. // of the number of texels needed to be covered in width and height order to filter the
  43648. // region. the bounding box for the center taps face is defined first, and if the
  43649. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  43650. // defined next
  43651. //--------------------------------------------------------------------------------------
  43652. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  43653. // note that pixels within these regions may be rejected
  43654. // based on the anlge
  43655. var iCubeFace;
  43656. var u;
  43657. var v;
  43658. // bounding box per face to specify region to process
  43659. var filterExtents = [];
  43660. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43661. filterExtents.push(new CMGBoundinBox());
  43662. }
  43663. // min angle a src texel can cover (in degrees)
  43664. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  43665. // angle about center tap to define filter cone
  43666. // filter angle is 1/2 the cone angle
  43667. var filterAngle = filterConeAngle / 2.0;
  43668. //ensure filter angle is larger than a texel
  43669. if (filterAngle < srcTexelAngle) {
  43670. filterAngle = srcTexelAngle;
  43671. }
  43672. //ensure filter cone is always smaller than the hemisphere
  43673. if (filterAngle > 90.0) {
  43674. filterAngle = 90.0;
  43675. }
  43676. // the maximum number of texels in 1D the filter cone angle will cover
  43677. // used to determine bounding box size for filter extents
  43678. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  43679. // ensure conservative region always covers at least one texel
  43680. if (filterSize < 1) {
  43681. filterSize = 1;
  43682. }
  43683. // dotProdThresh threshold based on cone angle to determine whether or not taps
  43684. // reside within the cone angle
  43685. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  43686. // process required faces
  43687. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43688. //iterate over dst cube map face texel
  43689. for (v = 0; v < dstSize; v++) {
  43690. for (u = 0; u < dstSize; u++) {
  43691. //get center tap direction
  43692. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  43693. //clear old per-face filter extents
  43694. this.clearFilterExtents(filterExtents);
  43695. //define per-face filter extents
  43696. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  43697. //perform filtering of src faces using filter extents
  43698. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  43699. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  43700. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  43701. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  43702. }
  43703. }
  43704. }
  43705. };
  43706. //--------------------------------------------------------------------------------------
  43707. //Clear filter extents for the 6 cube map faces
  43708. //--------------------------------------------------------------------------------------
  43709. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  43710. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  43711. filterExtents[iCubeFaces].clear();
  43712. }
  43713. };
  43714. //--------------------------------------------------------------------------------------
  43715. //Define per-face bounding box filter extents
  43716. //
  43717. // These define conservative texel regions in each of the faces the filter can possibly
  43718. // process. When the pixels in the regions are actually processed, the dot product
  43719. // between the tap vector and the center tap vector is used to determine the weight of
  43720. // the tap and whether or not the tap is within the cone.
  43721. //
  43722. //--------------------------------------------------------------------------------------
  43723. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  43724. //neighboring face and bleed over amount, and width of BBOX for
  43725. // left, right, top, and bottom edges of this face
  43726. var bleedOverAmount = [0, 0, 0, 0];
  43727. var bleedOverBBoxMin = [0, 0, 0, 0];
  43728. var bleedOverBBoxMax = [0, 0, 0, 0];
  43729. var neighborFace;
  43730. var neighborEdge;
  43731. var oppositeFaceIdx;
  43732. //get face idx, and u, v info from center tap dir
  43733. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  43734. var faceIdx = result.x;
  43735. var u = result.y;
  43736. var v = result.z;
  43737. //define bbox size within face
  43738. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  43739. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  43740. filterExtents[faceIdx].clampMin(0, 0, 0);
  43741. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  43742. //u and v extent in face corresponding to center tap
  43743. var minU = filterExtents[faceIdx].min.x;
  43744. var minV = filterExtents[faceIdx].min.y;
  43745. var maxU = filterExtents[faceIdx].max.x;
  43746. var maxV = filterExtents[faceIdx].max.y;
  43747. //bleed over amounts for face across u=0 edge (left)
  43748. bleedOverAmount[0] = (bboxSize - u);
  43749. bleedOverBBoxMin[0] = minV;
  43750. bleedOverBBoxMax[0] = maxV;
  43751. //bleed over amounts for face across u=1 edge (right)
  43752. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  43753. bleedOverBBoxMin[1] = minV;
  43754. bleedOverBBoxMax[1] = maxV;
  43755. //bleed over to face across v=0 edge (up)
  43756. bleedOverAmount[2] = (bboxSize - v);
  43757. bleedOverBBoxMin[2] = minU;
  43758. bleedOverBBoxMax[2] = maxU;
  43759. //bleed over to face across v=1 edge (down)
  43760. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  43761. bleedOverBBoxMin[3] = minU;
  43762. bleedOverBBoxMax[3] = maxU;
  43763. //compute bleed over regions in neighboring faces
  43764. for (var i = 0; i < 4; i++) {
  43765. if (bleedOverAmount[i] > 0) {
  43766. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  43767. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  43768. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  43769. // be flipped: the cases are
  43770. // if a left edge mates with a left or bottom edge on the neighbor
  43771. // if a top edge mates with a top or right edge on the neighbor
  43772. // if a right edge mates with a right or top edge on the neighbor
  43773. // if a bottom edge mates with a bottom or left edge on the neighbor
  43774. //Seeing as the edges are enumerated as follows
  43775. // left =0
  43776. // right =1
  43777. // top =2
  43778. // bottom =3
  43779. //
  43780. // so if the edge enums are the same, or the sum of the enums == 3,
  43781. // the bbox needs to be flipped
  43782. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  43783. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  43784. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  43785. }
  43786. //The way the bounding box is extended onto the neighboring face
  43787. // depends on which edge of neighboring face abuts with this one
  43788. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  43789. case PMREMGenerator.CP_EDGE_LEFT:
  43790. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  43791. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43792. break;
  43793. case PMREMGenerator.CP_EDGE_RIGHT:
  43794. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  43795. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43796. break;
  43797. case PMREMGenerator.CP_EDGE_TOP:
  43798. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  43799. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  43800. break;
  43801. case PMREMGenerator.CP_EDGE_BOTTOM:
  43802. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  43803. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  43804. break;
  43805. }
  43806. //clamp filter extents in non-center tap faces to remain within surface
  43807. filterExtents[neighborFace].clampMin(0, 0, 0);
  43808. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  43809. }
  43810. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  43811. // from the center tap face, then process the opposite face entirely for now.
  43812. //Note that the cases in which this happens, what usually happens is that
  43813. // more than one edge bleeds onto the opposite face, and the bounding box
  43814. // encompasses the entire cube map face.
  43815. if (bleedOverAmount[i] > srcSize) {
  43816. //determine opposite face
  43817. switch (faceIdx) {
  43818. case PMREMGenerator.CP_FACE_X_POS:
  43819. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43820. break;
  43821. case PMREMGenerator.CP_FACE_X_NEG:
  43822. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  43823. break;
  43824. case PMREMGenerator.CP_FACE_Y_POS:
  43825. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43826. break;
  43827. case PMREMGenerator.CP_FACE_Y_NEG:
  43828. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43829. break;
  43830. case PMREMGenerator.CP_FACE_Z_POS:
  43831. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43832. break;
  43833. case PMREMGenerator.CP_FACE_Z_NEG:
  43834. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43835. break;
  43836. default:
  43837. break;
  43838. }
  43839. //just encompass entire face for now
  43840. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  43841. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  43842. }
  43843. }
  43844. };
  43845. //--------------------------------------------------------------------------------------
  43846. //ProcessFilterExtents
  43847. // Process bounding box in each cube face
  43848. //
  43849. //--------------------------------------------------------------------------------------
  43850. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  43851. //accumulators are 64-bit floats in order to have the precision needed
  43852. // over a summation of a large number of pixels
  43853. var dstAccum = [0, 0, 0, 0];
  43854. var weightAccum = 0;
  43855. var k = 0;
  43856. var nSrcChannels = this.numChannels;
  43857. // norm cube map and srcCubeMap have same face width
  43858. var faceWidth = srcSize;
  43859. //amount to add to pointer to move to next scanline in images
  43860. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  43861. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  43862. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  43863. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  43864. // iterate over cubefaces
  43865. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  43866. //if bbox is non empty
  43867. if (!filterExtents[iFaceIdx].empty()) {
  43868. var uStart = filterExtents[iFaceIdx].min.x;
  43869. var vStart = filterExtents[iFaceIdx].min.y;
  43870. var uEnd = filterExtents[iFaceIdx].max.x;
  43871. var vEnd = filterExtents[iFaceIdx].max.y;
  43872. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  43873. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  43874. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  43875. for (var v = vStart; v <= vEnd; v++) {
  43876. var normCubeRowWalk = 0;
  43877. var srcCubeRowWalk = 0;
  43878. for (var u = uStart; u <= uEnd; u++) {
  43879. //pointer to direction in cube map associated with texel
  43880. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  43881. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  43882. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  43883. //check dot product to see if texel is within cone
  43884. var tapDotProd = texelVectX * centerTapDir.x +
  43885. texelVectY * centerTapDir.y +
  43886. texelVectZ * centerTapDir.z;
  43887. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  43888. //solid angle stored in 4th channel of normalizer/solid angle cube map
  43889. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  43890. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  43891. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  43892. // so just adding one to specularpower do the trick.
  43893. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  43894. //iterate over channels
  43895. for (k = 0; k < nSrcChannels; k++) {
  43896. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  43897. srcCubeRowWalk++;
  43898. }
  43899. weightAccum += weight; //accumulate weight
  43900. }
  43901. else {
  43902. //step across source pixel
  43903. srcCubeRowWalk += nSrcChannels;
  43904. }
  43905. normCubeRowWalk += 4; // 4 channels per norm cube map.
  43906. }
  43907. startIndexNormCubeMap += normCubePitch;
  43908. startIndexSrcCubeMap += srcCubePitch;
  43909. }
  43910. }
  43911. }
  43912. //divide through by weights if weight is non zero
  43913. if (weightAccum != 0.0) {
  43914. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  43915. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  43916. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  43917. if (this.numChannels > 3) {
  43918. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  43919. }
  43920. }
  43921. else {
  43922. // otherwise sample nearest
  43923. // get face idx and u, v texel coordinate in face
  43924. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  43925. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  43926. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  43927. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  43928. if (this.numChannels > 3) {
  43929. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  43930. }
  43931. }
  43932. return PMREMGenerator._vectorTemp;
  43933. };
  43934. //--------------------------------------------------------------------------------------
  43935. // Fixup cube edges
  43936. //
  43937. // average texels on cube map faces across the edges
  43938. // WARP/BENT Method Only.
  43939. //--------------------------------------------------------------------------------------
  43940. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  43941. var k;
  43942. var j;
  43943. var i;
  43944. var iFace;
  43945. var iCorner = 0;
  43946. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  43947. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  43948. // note that if functionality to filter across the three texels for each corner, then
  43949. //indexed by corner and face idx. the array contains the face the start points belongs to.
  43950. var cornerPtr = [
  43951. [[], [], []],
  43952. [[], [], []],
  43953. [[], [], []],
  43954. [[], [], []],
  43955. [[], [], []],
  43956. [[], [], []],
  43957. [[], [], []],
  43958. [[], [], []]
  43959. ];
  43960. //if there is no fixup, or fixup width = 0, do nothing
  43961. if (cubeMapSize < 1) {
  43962. return;
  43963. }
  43964. //special case 1x1 cubemap, average face colors
  43965. if (cubeMapSize == 1) {
  43966. //iterate over channels
  43967. for (k = 0; k < this.numChannels; k++) {
  43968. var accum = 0.0;
  43969. //iterate over faces to accumulate face colors
  43970. for (iFace = 0; iFace < 6; iFace++) {
  43971. accum += cubeMap[iFace][k];
  43972. }
  43973. //compute average over 6 face colors
  43974. accum /= 6.0;
  43975. //iterate over faces to distribute face colors
  43976. for (iFace = 0; iFace < 6; iFace++) {
  43977. cubeMap[iFace][k] = accum;
  43978. }
  43979. }
  43980. return;
  43981. }
  43982. //iterate over faces to collect list of corner texel pointers
  43983. for (iFace = 0; iFace < 6; iFace++) {
  43984. //the 4 corner pointers for this face
  43985. faceCornerStartIndicies[0] = [iFace, 0];
  43986. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  43987. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  43988. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  43989. //iterate over face corners to collect cube corner pointers
  43990. for (iCorner = 0; iCorner < 4; iCorner++) {
  43991. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  43992. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  43993. cornerNumPtrs[corner]++;
  43994. }
  43995. }
  43996. //iterate over corners to average across corner tap values
  43997. for (iCorner = 0; iCorner < 8; iCorner++) {
  43998. for (k = 0; k < this.numChannels; k++) {
  43999. var cornerTapAccum = 0.0;
  44000. //iterate over corner texels and average results
  44001. for (i = 0; i < 3; i++) {
  44002. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  44003. }
  44004. //divide by 3 to compute average of corner tap values
  44005. cornerTapAccum *= (1.0 / 3.0);
  44006. //iterate over corner texels and average results
  44007. for (i = 0; i < 3; i++) {
  44008. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  44009. }
  44010. }
  44011. }
  44012. //iterate over the twelve edges of the cube to average across edges
  44013. for (i = 0; i < 12; i++) {
  44014. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  44015. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  44016. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  44017. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  44018. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  44019. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  44020. var edgeWalk = 0;
  44021. var neighborEdgeWalk = 0;
  44022. //Determine walking pointers based on edge type
  44023. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  44024. switch (edge) {
  44025. case PMREMGenerator.CP_EDGE_LEFT:
  44026. // no change to faceEdgeStartPtr
  44027. edgeWalk = this.numChannels * cubeMapSize;
  44028. break;
  44029. case PMREMGenerator.CP_EDGE_RIGHT:
  44030. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  44031. edgeWalk = this.numChannels * cubeMapSize;
  44032. break;
  44033. case PMREMGenerator.CP_EDGE_TOP:
  44034. // no change to faceEdgeStartPtr
  44035. edgeWalk = this.numChannels;
  44036. break;
  44037. case PMREMGenerator.CP_EDGE_BOTTOM:
  44038. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  44039. edgeWalk = this.numChannels;
  44040. break;
  44041. }
  44042. //For certain types of edge abutments, the neighbor edge walk needs to
  44043. // be flipped: the cases are
  44044. // if a left edge mates with a left or bottom edge on the neighbor
  44045. // if a top edge mates with a top or right edge on the neighbor
  44046. // if a right edge mates with a right or top edge on the neighbor
  44047. // if a bottom edge mates with a bottom or left edge on the neighbor
  44048. //Seeing as the edges are enumerated as follows
  44049. // left =0
  44050. // right =1
  44051. // top =2
  44052. // bottom =3
  44053. //
  44054. //If the edge enums are the same, or the sum of the enums == 3,
  44055. // the neighbor edge walk needs to be flipped
  44056. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  44057. switch (neighborEdge) {
  44058. case PMREMGenerator.CP_EDGE_LEFT:
  44059. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  44060. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  44061. break;
  44062. case PMREMGenerator.CP_EDGE_RIGHT:
  44063. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  44064. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  44065. break;
  44066. case PMREMGenerator.CP_EDGE_TOP:
  44067. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  44068. neighborEdgeWalk = -this.numChannels;
  44069. break;
  44070. case PMREMGenerator.CP_EDGE_BOTTOM:
  44071. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  44072. neighborEdgeWalk = -this.numChannels;
  44073. break;
  44074. }
  44075. }
  44076. else {
  44077. //swapped direction neighbor edge walk
  44078. switch (neighborEdge) {
  44079. case PMREMGenerator.CP_EDGE_LEFT:
  44080. //no change to neighborEdgeStartPtr for this case since it points
  44081. // to the upper left corner already
  44082. neighborEdgeWalk = this.numChannels * cubeMapSize;
  44083. break;
  44084. case PMREMGenerator.CP_EDGE_RIGHT:
  44085. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  44086. neighborEdgeWalk = this.numChannels * cubeMapSize;
  44087. break;
  44088. case PMREMGenerator.CP_EDGE_TOP:
  44089. //no change to neighborEdgeStartPtr for this case since it points
  44090. // to the upper left corner already
  44091. neighborEdgeWalk = this.numChannels;
  44092. break;
  44093. case PMREMGenerator.CP_EDGE_BOTTOM:
  44094. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  44095. neighborEdgeWalk = this.numChannels;
  44096. break;
  44097. }
  44098. }
  44099. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  44100. //nearby neighborhood
  44101. //step ahead one texel on edge
  44102. edgeStartIndex += edgeWalk;
  44103. neighborEdgeStartIndex += neighborEdgeWalk;
  44104. // note that this loop does not process the corner texels, since they have already been
  44105. // averaged across faces across earlier
  44106. for (j = 1; j < (cubeMapSize - 1); j++) {
  44107. //for each set of taps along edge, average them
  44108. // and rewrite the results into the edges
  44109. for (k = 0; k < this.numChannels; k++) {
  44110. var edgeTap = cubeMap[face][edgeStartIndex + k];
  44111. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  44112. //compute average of tap intensity values
  44113. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  44114. //propagate average of taps to edge taps
  44115. cubeMap[face][edgeStartIndex + k] = avgTap;
  44116. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  44117. }
  44118. edgeStartIndex += edgeWalk;
  44119. neighborEdgeStartIndex += neighborEdgeWalk;
  44120. }
  44121. }
  44122. };
  44123. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  44124. PMREMGenerator.CP_UDIR = 0;
  44125. PMREMGenerator.CP_VDIR = 1;
  44126. PMREMGenerator.CP_FACEAXIS = 2;
  44127. //used to index cube faces
  44128. PMREMGenerator.CP_FACE_X_POS = 0;
  44129. PMREMGenerator.CP_FACE_X_NEG = 1;
  44130. PMREMGenerator.CP_FACE_Y_POS = 2;
  44131. PMREMGenerator.CP_FACE_Y_NEG = 3;
  44132. PMREMGenerator.CP_FACE_Z_POS = 4;
  44133. PMREMGenerator.CP_FACE_Z_NEG = 5;
  44134. //used to index image edges
  44135. // NOTE.. the actual number corresponding to the edge is important
  44136. // do not change these, or the code will break
  44137. //
  44138. // CP_EDGE_LEFT is u = 0
  44139. // CP_EDGE_RIGHT is u = width-1
  44140. // CP_EDGE_TOP is v = 0
  44141. // CP_EDGE_BOTTOM is v = height-1
  44142. PMREMGenerator.CP_EDGE_LEFT = 0;
  44143. PMREMGenerator.CP_EDGE_RIGHT = 1;
  44144. PMREMGenerator.CP_EDGE_TOP = 2;
  44145. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  44146. //corners of CUBE map (P or N specifys if it corresponds to the
  44147. // positive or negative direction each of X, Y, and Z
  44148. PMREMGenerator.CP_CORNER_NNN = 0;
  44149. PMREMGenerator.CP_CORNER_NNP = 1;
  44150. PMREMGenerator.CP_CORNER_NPN = 2;
  44151. PMREMGenerator.CP_CORNER_NPP = 3;
  44152. PMREMGenerator.CP_CORNER_PNN = 4;
  44153. PMREMGenerator.CP_CORNER_PNP = 5;
  44154. PMREMGenerator.CP_CORNER_PPN = 6;
  44155. PMREMGenerator.CP_CORNER_PPP = 7;
  44156. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  44157. //3x2 matrices that map cube map indexing vectors in 3d
  44158. // (after face selection and divide through by the
  44159. // _ABSOLUTE VALUE_ of the max coord)
  44160. // into NVC space
  44161. //Note this currently assumes the D3D cube face ordering and orientation
  44162. PMREMGenerator._sgFace2DMapping = [
  44163. //XPOS face
  44164. [[0, 0, -1],
  44165. [0, -1, 0],
  44166. [1, 0, 0]],
  44167. //XNEG face
  44168. [[0, 0, 1],
  44169. [0, -1, 0],
  44170. [-1, 0, 0]],
  44171. //YPOS face
  44172. [[1, 0, 0],
  44173. [0, 0, 1],
  44174. [0, 1, 0]],
  44175. //YNEG face
  44176. [[1, 0, 0],
  44177. [0, 0, -1],
  44178. [0, -1, 0]],
  44179. //ZPOS face
  44180. [[1, 0, 0],
  44181. [0, -1, 0],
  44182. [0, 0, 1]],
  44183. //ZNEG face
  44184. [[-1, 0, 0],
  44185. [0, -1, 0],
  44186. [0, 0, -1]],
  44187. ];
  44188. //------------------------------------------------------------------------------
  44189. // D3D cube map face specification
  44190. // mapping from 3D x,y,z cube map lookup coordinates
  44191. // to 2D within face u,v coordinates
  44192. //
  44193. // --------------------> U direction
  44194. // | (within-face texture space)
  44195. // | _____
  44196. // | | |
  44197. // | | +Y |
  44198. // | _____|_____|_____ _____
  44199. // | | | | | |
  44200. // | | -X | +Z | +X | -Z |
  44201. // | |_____|_____|_____|_____|
  44202. // | | |
  44203. // | | -Y |
  44204. // | |_____|
  44205. // |
  44206. // v V direction
  44207. // (within-face texture space)
  44208. //------------------------------------------------------------------------------
  44209. //Information about neighbors and how texture coorrdinates change across faces
  44210. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  44211. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  44212. //Note this currently assumes the D3D cube face ordering and orientation
  44213. PMREMGenerator._sgCubeNgh = [
  44214. //XPOS face
  44215. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44216. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  44217. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44218. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  44219. //XNEG face
  44220. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  44221. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  44222. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  44223. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  44224. //YPOS face
  44225. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  44226. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  44227. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  44228. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  44229. //YNEG face
  44230. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  44231. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44232. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44233. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  44234. //ZPOS face
  44235. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  44236. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  44237. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44238. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  44239. //ZNEG face
  44240. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44241. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  44242. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  44243. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  44244. ];
  44245. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  44246. // this table is used to average over the edges.
  44247. PMREMGenerator._sgCubeEdgeList = [
  44248. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  44249. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44250. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  44251. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44252. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  44253. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  44254. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  44255. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  44256. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  44257. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44258. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  44259. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  44260. ];
  44261. //Information about which of the 8 cube corners are correspond to the
  44262. // the 4 corners in each cube face
  44263. // the order is upper left, upper right, lower left, lower right
  44264. PMREMGenerator._sgCubeCornerList = [
  44265. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  44266. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  44267. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  44268. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  44269. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  44270. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  44271. ];
  44272. return PMREMGenerator;
  44273. })();
  44274. Internals.PMREMGenerator = PMREMGenerator;
  44275. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44276. })(BABYLON || (BABYLON = {}));
  44277. var BABYLON;
  44278. (function (BABYLON) {
  44279. /**
  44280. * This represents a texture coming from an HDR input.
  44281. *
  44282. * The only supported format is currently panorama picture stored in RGBE format.
  44283. * Example of such files can be found on HDRLib: http://hdrlib.com/
  44284. */
  44285. var HDRCubeTexture = (function (_super) {
  44286. __extends(HDRCubeTexture, _super);
  44287. /**
  44288. * Instantiates an HDRTexture from the following parameters.
  44289. *
  44290. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  44291. * @param scene The scene the texture will be used in
  44292. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  44293. * @param noMipmap Forces to not generate the mipmap if true
  44294. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  44295. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  44296. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  44297. */
  44298. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  44299. if (noMipmap === void 0) { noMipmap = false; }
  44300. if (generateHarmonics === void 0) { generateHarmonics = true; }
  44301. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  44302. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  44303. _super.call(this, scene);
  44304. this._useInGammaSpace = false;
  44305. this._generateHarmonics = true;
  44306. this._isBABYLONPreprocessed = false;
  44307. /**
  44308. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  44309. */
  44310. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  44311. /**
  44312. * The spherical polynomial data extracted from the texture.
  44313. */
  44314. this.sphericalPolynomial = null;
  44315. /**
  44316. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  44317. * This is usefull at run time to apply the good shader.
  44318. */
  44319. this.isPMREM = false;
  44320. if (!url) {
  44321. return;
  44322. }
  44323. this.name = url;
  44324. this.url = url;
  44325. this.hasAlpha = false;
  44326. this.isCube = true;
  44327. this._textureMatrix = BABYLON.Matrix.Identity();
  44328. if (size) {
  44329. this._isBABYLONPreprocessed = false;
  44330. this._noMipmap = noMipmap;
  44331. this._size = size;
  44332. this._useInGammaSpace = useInGammaSpace;
  44333. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  44334. }
  44335. else {
  44336. this._isBABYLONPreprocessed = true;
  44337. this._noMipmap = false;
  44338. this._useInGammaSpace = false;
  44339. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD;
  44340. }
  44341. this.isPMREM = this._usePMREMGenerator;
  44342. this._texture = this._getFromCache(url, this._noMipmap);
  44343. if (!this._texture) {
  44344. if (!scene.useDelayedTextureLoading) {
  44345. this.loadTexture();
  44346. }
  44347. else {
  44348. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  44349. }
  44350. }
  44351. }
  44352. /**
  44353. * Occurs when the file is a preprocessed .babylon.hdr file.
  44354. */
  44355. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  44356. var _this = this;
  44357. var mipLevels = 0;
  44358. var floatArrayView = null;
  44359. var mipmapGenerator = function (data) {
  44360. var mips = [];
  44361. var startIndex = 30;
  44362. for (var level = 0; level < mipLevels; level++) {
  44363. mips.push([]);
  44364. // Fill each pixel of the mip level.
  44365. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  44366. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44367. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  44368. mips[level].push(faceData);
  44369. startIndex += faceSize;
  44370. }
  44371. }
  44372. return mips;
  44373. };
  44374. var callback = function (buffer) {
  44375. // Create Native Array Views
  44376. var intArrayView = new Int32Array(buffer);
  44377. floatArrayView = new Float32Array(buffer);
  44378. // Fill header.
  44379. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  44380. _this._size = intArrayView[1]; // CubeMap max mip face size.
  44381. // Update Texture Information.
  44382. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  44383. // Fill polynomial information.
  44384. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  44385. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  44386. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  44387. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  44388. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  44389. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  44390. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  44391. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  44392. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  44393. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  44394. // Fill pixel data.
  44395. mipLevels = intArrayView[29]; // Number of mip levels.
  44396. var startIndex = 30;
  44397. var data = [];
  44398. var faceSize = Math.pow(_this._size, 2) * 3;
  44399. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44400. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  44401. }
  44402. var results = [];
  44403. var byteArray = null;
  44404. // Create uintarray fallback.
  44405. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  44406. // 3 channels of 1 bytes per pixel in bytes.
  44407. var byteBuffer = new ArrayBuffer(faceSize);
  44408. byteArray = new Uint8Array(byteBuffer);
  44409. mipmapGenerator = null;
  44410. }
  44411. // Push each faces.
  44412. for (var j = 0; j < 6; j++) {
  44413. var dataFace = data[j];
  44414. // If special cases.
  44415. if (_this._useInGammaSpace || byteArray) {
  44416. for (var i = 0; i < _this._size * _this._size; i++) {
  44417. // Put in gamma space if requested.
  44418. if (_this._useInGammaSpace) {
  44419. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  44420. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  44421. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  44422. }
  44423. // Convert to int texture for fallback.
  44424. if (byteArray) {
  44425. // R
  44426. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  44427. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  44428. // G
  44429. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  44430. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  44431. // B
  44432. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  44433. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  44434. }
  44435. }
  44436. }
  44437. results.push(dataFace);
  44438. }
  44439. return results;
  44440. };
  44441. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  44442. };
  44443. /**
  44444. * Occurs when the file is raw .hdr file.
  44445. */
  44446. HDRCubeTexture.prototype.loadHDRTexture = function () {
  44447. var _this = this;
  44448. var callback = function (buffer) {
  44449. // Extract the raw linear data.
  44450. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  44451. // Generate harmonics if needed.
  44452. if (_this._generateHarmonics) {
  44453. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  44454. }
  44455. var results = [];
  44456. var byteArray = null;
  44457. // Create uintarray fallback.
  44458. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  44459. // 3 channels of 1 bytes per pixel in bytes.
  44460. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  44461. byteArray = new Uint8Array(byteBuffer);
  44462. }
  44463. // Push each faces.
  44464. for (var j = 0; j < 6; j++) {
  44465. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  44466. // If special cases.
  44467. if (_this._useInGammaSpace || byteArray) {
  44468. for (var i = 0; i < _this._size * _this._size; i++) {
  44469. // Put in gamma space if requested.
  44470. if (_this._useInGammaSpace) {
  44471. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  44472. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  44473. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  44474. }
  44475. // Convert to int texture for fallback.
  44476. if (byteArray) {
  44477. // R
  44478. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  44479. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  44480. // G
  44481. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  44482. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  44483. // B
  44484. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  44485. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  44486. }
  44487. }
  44488. }
  44489. results.push(dataFace);
  44490. }
  44491. return results;
  44492. };
  44493. var mipmapGenerator = null;
  44494. if (!this._noMipmap && this._usePMREMGenerator) {
  44495. mipmapGenerator = function (data) {
  44496. // Custom setup of the generator matching with the PBR shader values.
  44497. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  44498. return generator.filterCubeMap();
  44499. };
  44500. }
  44501. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  44502. };
  44503. /**
  44504. * Starts the loading process of the texture.
  44505. */
  44506. HDRCubeTexture.prototype.loadTexture = function () {
  44507. if (this._isBABYLONPreprocessed) {
  44508. this.loadBabylonTexture();
  44509. }
  44510. else {
  44511. this.loadHDRTexture();
  44512. }
  44513. };
  44514. HDRCubeTexture.prototype.clone = function () {
  44515. var size = this._isBABYLONPreprocessed ? null : this._size;
  44516. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  44517. // Base texture
  44518. newTexture.level = this.level;
  44519. newTexture.wrapU = this.wrapU;
  44520. newTexture.wrapV = this.wrapV;
  44521. newTexture.coordinatesIndex = this.coordinatesIndex;
  44522. newTexture.coordinatesMode = this.coordinatesMode;
  44523. return newTexture;
  44524. };
  44525. // Methods
  44526. HDRCubeTexture.prototype.delayLoad = function () {
  44527. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  44528. return;
  44529. }
  44530. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  44531. this._texture = this._getFromCache(this.url, this._noMipmap);
  44532. if (!this._texture) {
  44533. this.loadTexture();
  44534. }
  44535. };
  44536. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  44537. return this._textureMatrix;
  44538. };
  44539. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  44540. var texture = null;
  44541. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  44542. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  44543. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  44544. texture.name = parsedTexture.name;
  44545. texture.hasAlpha = parsedTexture.hasAlpha;
  44546. texture.level = parsedTexture.level;
  44547. texture.coordinatesMode = parsedTexture.coordinatesMode;
  44548. }
  44549. return texture;
  44550. };
  44551. HDRCubeTexture.prototype.serialize = function () {
  44552. if (!this.name) {
  44553. return null;
  44554. }
  44555. var serializationObject = {};
  44556. serializationObject.name = this.name;
  44557. serializationObject.hasAlpha = this.hasAlpha;
  44558. serializationObject.isCube = true;
  44559. serializationObject.level = this.level;
  44560. serializationObject.size = this._size;
  44561. serializationObject.coordinatesMode = this.coordinatesMode;
  44562. serializationObject.useInGammaSpace = this._useInGammaSpace;
  44563. serializationObject.generateHarmonics = this._generateHarmonics;
  44564. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  44565. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  44566. return serializationObject;
  44567. };
  44568. /**
  44569. * Saves as a file the data contained in the texture in a binary format.
  44570. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  44571. * as the spherical used in the lighting.
  44572. * @param url The HDR file url.
  44573. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  44574. * @param onError Method called if any error happens during download.
  44575. * @return The packed binary data.
  44576. */
  44577. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  44578. if (onError === void 0) { onError = null; }
  44579. var callback = function (buffer) {
  44580. var data = new Blob([buffer], { type: 'application/octet-stream' });
  44581. // Returns a URL you can use as a href.
  44582. var objUrl = window.URL.createObjectURL(data);
  44583. // Simulates a link to it and click to dowload.
  44584. var a = document.createElement("a");
  44585. document.body.appendChild(a);
  44586. a.style.display = "none";
  44587. a.href = objUrl;
  44588. a.download = "envmap.babylon.hdr";
  44589. a.click();
  44590. };
  44591. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  44592. };
  44593. /**
  44594. * Serializes the data contained in the texture in a binary format.
  44595. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  44596. * as the spherical used in the lighting.
  44597. * @param url The HDR file url.
  44598. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  44599. * @param onError Method called if any error happens during download.
  44600. * @return The packed binary data.
  44601. */
  44602. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  44603. if (onError === void 0) { onError = null; }
  44604. // Needs the url tho create the texture.
  44605. if (!url) {
  44606. return null;
  44607. }
  44608. // Check Power of two size.
  44609. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  44610. return null;
  44611. }
  44612. var getDataCallback = function (dataBuffer) {
  44613. // Extract the raw linear data.
  44614. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  44615. // Generate harmonics if needed.
  44616. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  44617. // Generate seamless faces
  44618. var mipGeneratorArray = [];
  44619. // Data are known to be in +X +Y +Z -X -Y -Z
  44620. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  44621. mipGeneratorArray.push(cubeData.right); // +X
  44622. mipGeneratorArray.push(cubeData.left); // -X
  44623. mipGeneratorArray.push(cubeData.up); // +Y
  44624. mipGeneratorArray.push(cubeData.down); // -Y
  44625. mipGeneratorArray.push(cubeData.front); // +Z
  44626. mipGeneratorArray.push(cubeData.back); // -Z
  44627. // Custom setup of the generator matching with the PBR shader values.
  44628. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  44629. var mippedData = generator.filterCubeMap();
  44630. // Compute required byte length.
  44631. var byteLength = 1 * 4; // Raw Data Version int32.
  44632. byteLength += 4; // CubeMap max mip face size int32.
  44633. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  44634. // Add data size.
  44635. byteLength += 4; // Number of mip levels int32.
  44636. for (var level = 0; level < mippedData.length; level++) {
  44637. var mipSize = size >> level;
  44638. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  44639. }
  44640. // Prepare binary structure.
  44641. var buffer = new ArrayBuffer(byteLength);
  44642. var intArrayView = new Int32Array(buffer);
  44643. var floatArrayView = new Float32Array(buffer);
  44644. // Fill header.
  44645. intArrayView[0] = 1; // Version 1.
  44646. intArrayView[1] = size; // CubeMap max mip face size.
  44647. // Fill polynomial information.
  44648. sphericalPolynomial.x.toArray(floatArrayView, 2);
  44649. sphericalPolynomial.y.toArray(floatArrayView, 5);
  44650. sphericalPolynomial.z.toArray(floatArrayView, 8);
  44651. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  44652. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  44653. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  44654. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  44655. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  44656. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  44657. // Fill pixel data.
  44658. intArrayView[29] = mippedData.length; // Number of mip levels.
  44659. var startIndex = 30;
  44660. for (var level = 0; level < mippedData.length; level++) {
  44661. // Fill each pixel of the mip level.
  44662. var faceSize = Math.pow(size >> level, 2) * 3;
  44663. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44664. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  44665. startIndex += faceSize;
  44666. }
  44667. }
  44668. // Callback.
  44669. callback(buffer);
  44670. };
  44671. // Download and process.
  44672. BABYLON.Tools.LoadFile(url, function (data) {
  44673. getDataCallback(data);
  44674. }, null, null, true, onError);
  44675. };
  44676. HDRCubeTexture._facesMapping = [
  44677. "right",
  44678. "up",
  44679. "front",
  44680. "left",
  44681. "down",
  44682. "back"
  44683. ];
  44684. return HDRCubeTexture;
  44685. })(BABYLON.BaseTexture);
  44686. BABYLON.HDRCubeTexture = HDRCubeTexture;
  44687. })(BABYLON || (BABYLON = {}));
  44688. var BABYLON;
  44689. (function (BABYLON) {
  44690. var Debug;
  44691. (function (Debug) {
  44692. /**
  44693. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  44694. */
  44695. var SkeletonViewer = (function () {
  44696. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  44697. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  44698. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  44699. this.skeleton = skeleton;
  44700. this.mesh = mesh;
  44701. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  44702. this.renderingGroupId = renderingGroupId;
  44703. this.color = BABYLON.Color3.White();
  44704. this._debugLines = [];
  44705. this._isEnabled = false;
  44706. this._scene = scene;
  44707. this.update();
  44708. this._renderFunction = this.update.bind(this);
  44709. }
  44710. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  44711. get: function () {
  44712. return this._isEnabled;
  44713. },
  44714. set: function (value) {
  44715. if (this._isEnabled === value) {
  44716. return;
  44717. }
  44718. this._isEnabled = value;
  44719. if (value) {
  44720. this._scene.registerBeforeRender(this._renderFunction);
  44721. }
  44722. else {
  44723. this._scene.unregisterBeforeRender(this._renderFunction);
  44724. }
  44725. },
  44726. enumerable: true,
  44727. configurable: true
  44728. });
  44729. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  44730. if (x === void 0) { x = 0; }
  44731. if (y === void 0) { y = 0; }
  44732. if (z === void 0) { z = 0; }
  44733. var tmat = BABYLON.Tmp.Matrix[0];
  44734. var parentBone = bone.getParent();
  44735. tmat.copyFrom(bone.getLocalMatrix());
  44736. if (x !== 0 || y !== 0 || z !== 0) {
  44737. var tmat2 = BABYLON.Tmp.Matrix[1];
  44738. BABYLON.Matrix.IdentityToRef(tmat2);
  44739. tmat2.m[12] = x;
  44740. tmat2.m[13] = y;
  44741. tmat2.m[14] = z;
  44742. tmat2.multiplyToRef(tmat, tmat);
  44743. }
  44744. if (parentBone) {
  44745. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  44746. }
  44747. tmat.multiplyToRef(meshMat, tmat);
  44748. position.x = tmat.m[12];
  44749. position.y = tmat.m[13];
  44750. position.z = tmat.m[14];
  44751. };
  44752. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  44753. var len = bones.length;
  44754. for (var i = 0; i < len; i++) {
  44755. var bone = bones[i];
  44756. var points = this._debugLines[i];
  44757. if (!points) {
  44758. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44759. this._debugLines[i] = points;
  44760. }
  44761. this._getBonePosition(points[0], bone, meshMat);
  44762. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  44763. }
  44764. };
  44765. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  44766. var len = bones.length;
  44767. var boneNum = 0;
  44768. for (var i = len - 1; i >= 0; i--) {
  44769. var childBone = bones[i];
  44770. var parentBone = childBone.getParent();
  44771. if (!parentBone) {
  44772. continue;
  44773. }
  44774. var points = this._debugLines[boneNum];
  44775. if (!points) {
  44776. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44777. this._debugLines[boneNum] = points;
  44778. }
  44779. this._getBonePosition(points[0], childBone, meshMat);
  44780. this._getBonePosition(points[1], parentBone, meshMat);
  44781. boneNum++;
  44782. }
  44783. };
  44784. SkeletonViewer.prototype.update = function () {
  44785. if (this.autoUpdateBonesMatrices) {
  44786. this._updateBoneMatrix(this.skeleton.bones[0]);
  44787. }
  44788. if (this.skeleton.bones[0].length === undefined) {
  44789. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44790. }
  44791. else {
  44792. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44793. }
  44794. if (!this._debugMesh) {
  44795. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  44796. this._debugMesh.renderingGroupId = this.renderingGroupId;
  44797. }
  44798. else {
  44799. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  44800. }
  44801. this._debugMesh.color = this.color;
  44802. };
  44803. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  44804. if (bone.getParent()) {
  44805. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  44806. }
  44807. var children = bone.children;
  44808. var len = children.length;
  44809. for (var i = 0; i < len; i++) {
  44810. this._updateBoneMatrix(children[i]);
  44811. }
  44812. };
  44813. SkeletonViewer.prototype.dispose = function () {
  44814. if (this._debugMesh) {
  44815. this.isEnabled = false;
  44816. this._debugMesh.dispose();
  44817. this._debugMesh = null;
  44818. }
  44819. };
  44820. return SkeletonViewer;
  44821. })();
  44822. Debug.SkeletonViewer = SkeletonViewer;
  44823. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44824. })(BABYLON || (BABYLON = {}));
  44825. var BABYLON;
  44826. (function (BABYLON) {
  44827. var maxSimultaneousLights = 4;
  44828. var PBRMaterialDefines = (function (_super) {
  44829. __extends(PBRMaterialDefines, _super);
  44830. function PBRMaterialDefines() {
  44831. _super.call(this);
  44832. this.ALBEDO = false;
  44833. this.AMBIENT = false;
  44834. this.OPACITY = false;
  44835. this.OPACITYRGB = false;
  44836. this.REFLECTION = false;
  44837. this.EMISSIVE = false;
  44838. this.REFLECTIVITY = false;
  44839. this.BUMP = false;
  44840. this.PARALLAX = false;
  44841. this.PARALLAXOCCLUSION = false;
  44842. this.SPECULAROVERALPHA = false;
  44843. this.CLIPPLANE = false;
  44844. this.ALPHATEST = false;
  44845. this.ALPHAFROMALBEDO = false;
  44846. this.POINTSIZE = false;
  44847. this.FOG = false;
  44848. this.LIGHT0 = false;
  44849. this.LIGHT1 = false;
  44850. this.LIGHT2 = false;
  44851. this.LIGHT3 = false;
  44852. this.SPOTLIGHT0 = false;
  44853. this.SPOTLIGHT1 = false;
  44854. this.SPOTLIGHT2 = false;
  44855. this.SPOTLIGHT3 = false;
  44856. this.HEMILIGHT0 = false;
  44857. this.HEMILIGHT1 = false;
  44858. this.HEMILIGHT2 = false;
  44859. this.HEMILIGHT3 = false;
  44860. this.POINTLIGHT0 = false;
  44861. this.POINTLIGHT1 = false;
  44862. this.POINTLIGHT2 = false;
  44863. this.POINTLIGHT3 = false;
  44864. this.DIRLIGHT0 = false;
  44865. this.DIRLIGHT1 = false;
  44866. this.DIRLIGHT2 = false;
  44867. this.DIRLIGHT3 = false;
  44868. this.SPECULARTERM = false;
  44869. this.SHADOW0 = false;
  44870. this.SHADOW1 = false;
  44871. this.SHADOW2 = false;
  44872. this.SHADOW3 = false;
  44873. this.SHADOWS = false;
  44874. this.SHADOWVSM0 = false;
  44875. this.SHADOWVSM1 = false;
  44876. this.SHADOWVSM2 = false;
  44877. this.SHADOWVSM3 = false;
  44878. this.SHADOWPCF0 = false;
  44879. this.SHADOWPCF1 = false;
  44880. this.SHADOWPCF2 = false;
  44881. this.SHADOWPCF3 = false;
  44882. this.OPACITYFRESNEL = false;
  44883. this.EMISSIVEFRESNEL = false;
  44884. this.FRESNEL = false;
  44885. this.NORMAL = false;
  44886. this.UV1 = false;
  44887. this.UV2 = false;
  44888. this.VERTEXCOLOR = false;
  44889. this.VERTEXALPHA = false;
  44890. this.NUM_BONE_INFLUENCERS = 0;
  44891. this.BonesPerMesh = 0;
  44892. this.INSTANCES = false;
  44893. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44894. this.MICROSURFACEAUTOMATIC = false;
  44895. this.EMISSIVEASILLUMINATION = false;
  44896. this.LINKEMISSIVEWITHALBEDO = false;
  44897. this.LIGHTMAP = false;
  44898. this.USELIGHTMAPASSHADOWMAP = false;
  44899. this.REFLECTIONMAP_3D = false;
  44900. this.REFLECTIONMAP_SPHERICAL = false;
  44901. this.REFLECTIONMAP_PLANAR = false;
  44902. this.REFLECTIONMAP_CUBIC = false;
  44903. this.REFLECTIONMAP_PROJECTION = false;
  44904. this.REFLECTIONMAP_SKYBOX = false;
  44905. this.REFLECTIONMAP_EXPLICIT = false;
  44906. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44907. this.INVERTCUBICMAP = false;
  44908. this.LOGARITHMICDEPTH = false;
  44909. this.CAMERATONEMAP = false;
  44910. this.CAMERACONTRAST = false;
  44911. this.OVERLOADEDVALUES = false;
  44912. this.OVERLOADEDSHADOWVALUES = false;
  44913. this.USESPHERICALFROMREFLECTIONMAP = false;
  44914. this.REFRACTION = false;
  44915. this.REFRACTIONMAP_3D = false;
  44916. this.LINKREFRACTIONTOTRANSPARENCY = false;
  44917. this.REFRACTIONMAPINLINEARSPACE = false;
  44918. this.LODBASEDMICROSFURACE = false;
  44919. this.USEPHYSICALLIGHTFALLOFF = false;
  44920. this.RADIANCEOVERALPHA = false;
  44921. this.USEPMREMREFLECTION = false;
  44922. this.USEPMREMREFRACTION = false;
  44923. this._keys = Object.keys(this);
  44924. }
  44925. return PBRMaterialDefines;
  44926. })(BABYLON.MaterialDefines);
  44927. /**
  44928. * The Physically based material of BJS.
  44929. *
  44930. * This offers the main features of a standard PBR material.
  44931. * For more information, please refer to the documentation :
  44932. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44933. */
  44934. var PBRMaterial = (function (_super) {
  44935. __extends(PBRMaterial, _super);
  44936. /**
  44937. * Instantiates a new PBRMaterial instance.
  44938. *
  44939. * @param name The material name
  44940. * @param scene The scene the material will be use in.
  44941. */
  44942. function PBRMaterial(name, scene) {
  44943. var _this = this;
  44944. _super.call(this, name, scene);
  44945. /**
  44946. * Intensity of the direct lights e.g. the four lights available in your scene.
  44947. * This impacts both the direct diffuse and specular highlights.
  44948. */
  44949. this.directIntensity = 1.0;
  44950. /**
  44951. * Intensity of the emissive part of the material.
  44952. * This helps controlling the emissive effect without modifying the emissive color.
  44953. */
  44954. this.emissiveIntensity = 1.0;
  44955. /**
  44956. * Intensity of the environment e.g. how much the environment will light the object
  44957. * either through harmonics for rough material or through the refelction for shiny ones.
  44958. */
  44959. this.environmentIntensity = 1.0;
  44960. /**
  44961. * This is a special control allowing the reduction of the specular highlights coming from the
  44962. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44963. */
  44964. this.specularIntensity = 1.0;
  44965. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  44966. /**
  44967. * Debug Control allowing disabling the bump map on this material.
  44968. */
  44969. this.disableBumpMap = false;
  44970. /**
  44971. * Debug Control helping enforcing or dropping the darkness of shadows.
  44972. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  44973. */
  44974. this.overloadedShadowIntensity = 1.0;
  44975. /**
  44976. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  44977. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  44978. */
  44979. this.overloadedShadeIntensity = 1.0;
  44980. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  44981. /**
  44982. * The camera exposure used on this material.
  44983. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44984. * This corresponds to a photographic exposure.
  44985. */
  44986. this.cameraExposure = 1.0;
  44987. /**
  44988. * The camera contrast used on this material.
  44989. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  44990. */
  44991. this.cameraContrast = 1.0;
  44992. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  44993. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  44994. /**
  44995. * Debug Control allowing to overload the ambient color.
  44996. * This as to be use with the overloadedAmbientIntensity parameter.
  44997. */
  44998. this.overloadedAmbient = BABYLON.Color3.White();
  44999. /**
  45000. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  45001. */
  45002. this.overloadedAmbientIntensity = 0.0;
  45003. /**
  45004. * Debug Control allowing to overload the albedo color.
  45005. * This as to be use with the overloadedAlbedoIntensity parameter.
  45006. */
  45007. this.overloadedAlbedo = BABYLON.Color3.White();
  45008. /**
  45009. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  45010. */
  45011. this.overloadedAlbedoIntensity = 0.0;
  45012. /**
  45013. * Debug Control allowing to overload the reflectivity color.
  45014. * This as to be use with the overloadedReflectivityIntensity parameter.
  45015. */
  45016. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  45017. /**
  45018. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  45019. */
  45020. this.overloadedReflectivityIntensity = 0.0;
  45021. /**
  45022. * Debug Control allowing to overload the emissive color.
  45023. * This as to be use with the overloadedEmissiveIntensity parameter.
  45024. */
  45025. this.overloadedEmissive = BABYLON.Color3.White();
  45026. /**
  45027. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  45028. */
  45029. this.overloadedEmissiveIntensity = 0.0;
  45030. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  45031. /**
  45032. * Debug Control allowing to overload the reflection color.
  45033. * This as to be use with the overloadedReflectionIntensity parameter.
  45034. */
  45035. this.overloadedReflection = BABYLON.Color3.White();
  45036. /**
  45037. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  45038. */
  45039. this.overloadedReflectionIntensity = 0.0;
  45040. /**
  45041. * Debug Control allowing to overload the microsurface.
  45042. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  45043. */
  45044. this.overloadedMicroSurface = 0.0;
  45045. /**
  45046. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  45047. */
  45048. this.overloadedMicroSurfaceIntensity = 0.0;
  45049. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  45050. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45051. /**
  45052. * AKA Diffuse Color in other nomenclature.
  45053. */
  45054. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45055. /**
  45056. * AKA Specular Color in other nomenclature.
  45057. */
  45058. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45059. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  45060. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45061. /**
  45062. * AKA Glossiness in other nomenclature.
  45063. */
  45064. this.microSurface = 0.9;
  45065. /**
  45066. * source material index of refraction (IOR)' / 'destination material IOR.
  45067. */
  45068. this.indexOfRefraction = 0.66;
  45069. /**
  45070. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45071. */
  45072. this.invertRefractionY = false;
  45073. /**
  45074. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45075. * Materials half opaque for instance using refraction could benefit from this control.
  45076. */
  45077. this.linkRefractionWithTransparency = false;
  45078. /**
  45079. * The emissive and albedo are linked to never be more than one (Energy conservation).
  45080. */
  45081. this.linkEmissiveWithAlbedo = false;
  45082. this.useLightmapAsShadowmap = false;
  45083. /**
  45084. * In this mode, the emissive informtaion will always be added to the lighting once.
  45085. * A light for instance can be thought as emissive.
  45086. */
  45087. this.useEmissiveAsIllumination = false;
  45088. /**
  45089. * Secifies that the alpha is coming form the albedo channel alpha channel.
  45090. */
  45091. this.useAlphaFromAlbedoTexture = false;
  45092. /**
  45093. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45094. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45095. */
  45096. this.useSpecularOverAlpha = true;
  45097. /**
  45098. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45099. */
  45100. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45101. /**
  45102. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45103. * The material will try to infer what glossiness each pixel should be.
  45104. */
  45105. this.useAutoMicroSurfaceFromReflectivityMap = false;
  45106. /**
  45107. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  45108. * the creation of the material.
  45109. */
  45110. this.useScalarInLinearSpace = false;
  45111. /**
  45112. * BJS is using an harcoded light falloff based on a manually sets up range.
  45113. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45114. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45115. */
  45116. this.usePhysicalLightFalloff = true;
  45117. /**
  45118. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45119. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45120. */
  45121. this.useRadianceOverAlpha = true;
  45122. /**
  45123. * Allows using the bump map in parallax mode.
  45124. */
  45125. this.useParallax = false;
  45126. /**
  45127. * Allows using the bump map in parallax occlusion mode.
  45128. */
  45129. this.useParallaxOcclusion = false;
  45130. /**
  45131. * Controls the scale bias of the parallax mode.
  45132. */
  45133. this.parallaxScaleBias = 0.05;
  45134. this.disableLighting = false;
  45135. this._renderTargets = new BABYLON.SmartArray(16);
  45136. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  45137. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45138. this._tempColor = new BABYLON.Color3();
  45139. this._defines = new PBRMaterialDefines();
  45140. this._cachedDefines = new PBRMaterialDefines();
  45141. this._myScene = null;
  45142. this._myShadowGenerator = null;
  45143. this._cachedDefines.BonesPerMesh = -1;
  45144. this.getRenderTargetTextures = function () {
  45145. _this._renderTargets.reset();
  45146. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  45147. _this._renderTargets.push(_this.reflectionTexture);
  45148. }
  45149. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  45150. _this._renderTargets.push(_this.refractionTexture);
  45151. }
  45152. return _this._renderTargets;
  45153. };
  45154. }
  45155. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  45156. get: function () {
  45157. return this._useLogarithmicDepth;
  45158. },
  45159. set: function (value) {
  45160. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45161. },
  45162. enumerable: true,
  45163. configurable: true
  45164. });
  45165. PBRMaterial.prototype.needAlphaBlending = function () {
  45166. if (this.linkRefractionWithTransparency) {
  45167. return false;
  45168. }
  45169. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  45170. };
  45171. PBRMaterial.prototype.needAlphaTesting = function () {
  45172. if (this.linkRefractionWithTransparency) {
  45173. return false;
  45174. }
  45175. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  45176. };
  45177. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45178. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  45179. };
  45180. PBRMaterial.prototype.getAlphaTestTexture = function () {
  45181. return this.albedoTexture;
  45182. };
  45183. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  45184. if (!mesh) {
  45185. return true;
  45186. }
  45187. if (this._defines.INSTANCES !== useInstances) {
  45188. return false;
  45189. }
  45190. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  45191. return true;
  45192. }
  45193. return false;
  45194. };
  45195. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  45196. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  45197. };
  45198. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  45199. if (!useScalarInLinear) {
  45200. color.toLinearSpaceToRef(ref);
  45201. }
  45202. else {
  45203. ref.r = color.r;
  45204. ref.g = color.g;
  45205. ref.b = color.b;
  45206. }
  45207. };
  45208. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace) {
  45209. var lightIndex = 0;
  45210. var depthValuesAlreadySet = false;
  45211. for (var index = 0; index < scene.lights.length; index++) {
  45212. var light = scene.lights[index];
  45213. if (!light.isEnabled()) {
  45214. continue;
  45215. }
  45216. if (!light.canAffectMesh(mesh)) {
  45217. continue;
  45218. }
  45219. this._lightRadiuses[lightIndex] = light.radius;
  45220. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  45221. // GAMMA CORRECTION.
  45222. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  45223. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  45224. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
  45225. if (defines["SPECULARTERM"]) {
  45226. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  45227. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  45228. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  45229. }
  45230. // Shadows
  45231. if (scene.shadowsEnabled) {
  45232. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  45233. }
  45234. lightIndex++;
  45235. if (lightIndex === maxSimultaneousLights)
  45236. break;
  45237. }
  45238. effect.setFloat4("vLightRadiuses", this._lightRadiuses[0], this._lightRadiuses[1], this._lightRadiuses[2], this._lightRadiuses[3]);
  45239. };
  45240. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  45241. if (this.checkReadyOnlyOnce) {
  45242. if (this._wasPreviouslyReady) {
  45243. return true;
  45244. }
  45245. }
  45246. var scene = this.getScene();
  45247. if (!this.checkReadyOnEveryCall) {
  45248. if (this._renderId === scene.getRenderId()) {
  45249. if (this._checkCache(scene, mesh, useInstances)) {
  45250. return true;
  45251. }
  45252. }
  45253. }
  45254. var engine = scene.getEngine();
  45255. var needNormals = false;
  45256. var needUVs = false;
  45257. this._defines.reset();
  45258. if (scene.texturesEnabled) {
  45259. // Textures
  45260. if (scene.texturesEnabled) {
  45261. if (scene.getEngine().getCaps().textureLOD) {
  45262. this._defines.LODBASEDMICROSFURACE = true;
  45263. }
  45264. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45265. if (!this.albedoTexture.isReady()) {
  45266. return false;
  45267. }
  45268. else {
  45269. needUVs = true;
  45270. this._defines.ALBEDO = true;
  45271. }
  45272. }
  45273. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45274. if (!this.ambientTexture.isReady()) {
  45275. return false;
  45276. }
  45277. else {
  45278. needUVs = true;
  45279. this._defines.AMBIENT = true;
  45280. }
  45281. }
  45282. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45283. if (!this.opacityTexture.isReady()) {
  45284. return false;
  45285. }
  45286. else {
  45287. needUVs = true;
  45288. this._defines.OPACITY = true;
  45289. if (this.opacityTexture.getAlphaFromRGB) {
  45290. this._defines.OPACITYRGB = true;
  45291. }
  45292. }
  45293. }
  45294. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45295. if (!this.reflectionTexture.isReady()) {
  45296. return false;
  45297. }
  45298. else {
  45299. needNormals = true;
  45300. this._defines.REFLECTION = true;
  45301. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45302. this._defines.INVERTCUBICMAP = true;
  45303. }
  45304. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  45305. switch (this.reflectionTexture.coordinatesMode) {
  45306. case BABYLON.Texture.CUBIC_MODE:
  45307. case BABYLON.Texture.INVCUBIC_MODE:
  45308. this._defines.REFLECTIONMAP_CUBIC = true;
  45309. break;
  45310. case BABYLON.Texture.EXPLICIT_MODE:
  45311. this._defines.REFLECTIONMAP_EXPLICIT = true;
  45312. break;
  45313. case BABYLON.Texture.PLANAR_MODE:
  45314. this._defines.REFLECTIONMAP_PLANAR = true;
  45315. break;
  45316. case BABYLON.Texture.PROJECTION_MODE:
  45317. this._defines.REFLECTIONMAP_PROJECTION = true;
  45318. break;
  45319. case BABYLON.Texture.SKYBOX_MODE:
  45320. this._defines.REFLECTIONMAP_SKYBOX = true;
  45321. break;
  45322. case BABYLON.Texture.SPHERICAL_MODE:
  45323. this._defines.REFLECTIONMAP_SPHERICAL = true;
  45324. break;
  45325. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45326. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45327. break;
  45328. }
  45329. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  45330. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  45331. needNormals = true;
  45332. if (this.reflectionTexture.isPMREM) {
  45333. this._defines.USEPMREMREFLECTION = true;
  45334. }
  45335. }
  45336. }
  45337. }
  45338. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45339. if (!this.lightmapTexture.isReady()) {
  45340. return false;
  45341. }
  45342. else {
  45343. needUVs = true;
  45344. this._defines.LIGHTMAP = true;
  45345. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  45346. }
  45347. }
  45348. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45349. if (!this.emissiveTexture.isReady()) {
  45350. return false;
  45351. }
  45352. else {
  45353. needUVs = true;
  45354. this._defines.EMISSIVE = true;
  45355. }
  45356. }
  45357. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45358. if (!this.reflectivityTexture.isReady()) {
  45359. return false;
  45360. }
  45361. else {
  45362. needUVs = true;
  45363. this._defines.REFLECTIVITY = true;
  45364. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  45365. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  45366. }
  45367. }
  45368. }
  45369. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  45370. if (!this.bumpTexture.isReady()) {
  45371. return false;
  45372. }
  45373. else {
  45374. needUVs = true;
  45375. this._defines.BUMP = true;
  45376. if (this.useParallax) {
  45377. this._defines.PARALLAX = true;
  45378. if (this.useParallaxOcclusion) {
  45379. this._defines.PARALLAXOCCLUSION = true;
  45380. }
  45381. }
  45382. }
  45383. }
  45384. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45385. if (!this.refractionTexture.isReady()) {
  45386. return false;
  45387. }
  45388. else {
  45389. needUVs = true;
  45390. this._defines.REFRACTION = true;
  45391. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  45392. if (this.linkRefractionWithTransparency) {
  45393. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45394. }
  45395. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  45396. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  45397. if (this.refractionTexture.isPMREM) {
  45398. this._defines.USEPMREMREFRACTION = true;
  45399. }
  45400. }
  45401. }
  45402. }
  45403. }
  45404. // Effect
  45405. if (scene.clipPlane) {
  45406. this._defines.CLIPPLANE = true;
  45407. }
  45408. if (engine.getAlphaTesting()) {
  45409. this._defines.ALPHATEST = true;
  45410. }
  45411. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45412. this._defines.ALPHAFROMALBEDO = true;
  45413. }
  45414. if (this.useEmissiveAsIllumination) {
  45415. this._defines.EMISSIVEASILLUMINATION = true;
  45416. }
  45417. if (this.linkEmissiveWithAlbedo) {
  45418. this._defines.LINKEMISSIVEWITHALBEDO = true;
  45419. }
  45420. if (this.useLogarithmicDepth) {
  45421. this._defines.LOGARITHMICDEPTH = true;
  45422. }
  45423. if (this.cameraContrast != 1) {
  45424. this._defines.CAMERACONTRAST = true;
  45425. }
  45426. if (this.cameraExposure != 1) {
  45427. this._defines.CAMERATONEMAP = true;
  45428. }
  45429. if (this.overloadedShadeIntensity != 1 ||
  45430. this.overloadedShadowIntensity != 1) {
  45431. this._defines.OVERLOADEDSHADOWVALUES = true;
  45432. }
  45433. if (this.overloadedMicroSurfaceIntensity > 0 ||
  45434. this.overloadedEmissiveIntensity > 0 ||
  45435. this.overloadedReflectivityIntensity > 0 ||
  45436. this.overloadedAlbedoIntensity > 0 ||
  45437. this.overloadedAmbientIntensity > 0 ||
  45438. this.overloadedReflectionIntensity > 0) {
  45439. this._defines.OVERLOADEDVALUES = true;
  45440. }
  45441. // Point size
  45442. if (this.pointsCloud || scene.forcePointsCloud) {
  45443. this._defines.POINTSIZE = true;
  45444. }
  45445. // Fog
  45446. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45447. this._defines.FOG = true;
  45448. }
  45449. if (scene.lightsEnabled && !this.disableLighting) {
  45450. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
  45451. }
  45452. if (BABYLON.StandardMaterial.FresnelEnabled) {
  45453. // Fresnel
  45454. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  45455. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  45456. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  45457. this._defines.OPACITYFRESNEL = true;
  45458. }
  45459. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  45460. this._defines.EMISSIVEFRESNEL = true;
  45461. }
  45462. needNormals = true;
  45463. this._defines.FRESNEL = true;
  45464. }
  45465. }
  45466. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  45467. this._defines.SPECULAROVERALPHA = true;
  45468. }
  45469. if (this.usePhysicalLightFalloff) {
  45470. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  45471. }
  45472. if (this.useRadianceOverAlpha) {
  45473. this._defines.RADIANCEOVERALPHA = true;
  45474. }
  45475. // Attribs
  45476. if (mesh) {
  45477. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45478. this._defines.NORMAL = true;
  45479. }
  45480. if (needUVs) {
  45481. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45482. this._defines.UV1 = true;
  45483. }
  45484. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45485. this._defines.UV2 = true;
  45486. }
  45487. }
  45488. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  45489. this._defines.VERTEXCOLOR = true;
  45490. if (mesh.hasVertexAlpha) {
  45491. this._defines.VERTEXALPHA = true;
  45492. }
  45493. }
  45494. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45495. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  45496. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  45497. }
  45498. // Instances
  45499. if (useInstances) {
  45500. this._defines.INSTANCES = true;
  45501. }
  45502. }
  45503. // Get correct effect
  45504. if (!this._defines.isEqual(this._cachedDefines)) {
  45505. this._defines.cloneTo(this._cachedDefines);
  45506. scene.resetCachedMaterial();
  45507. // Fallbacks
  45508. var fallbacks = new BABYLON.EffectFallbacks();
  45509. if (this._defines.REFLECTION) {
  45510. fallbacks.addFallback(0, "REFLECTION");
  45511. }
  45512. if (this._defines.REFRACTION) {
  45513. fallbacks.addFallback(0, "REFRACTION");
  45514. }
  45515. if (this._defines.REFLECTIVITY) {
  45516. fallbacks.addFallback(0, "REFLECTIVITY");
  45517. }
  45518. if (this._defines.BUMP) {
  45519. fallbacks.addFallback(0, "BUMP");
  45520. }
  45521. if (this._defines.PARALLAX) {
  45522. fallbacks.addFallback(1, "PARALLAX");
  45523. }
  45524. if (this._defines.PARALLAXOCCLUSION) {
  45525. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  45526. }
  45527. if (this._defines.SPECULAROVERALPHA) {
  45528. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  45529. }
  45530. if (this._defines.FOG) {
  45531. fallbacks.addFallback(1, "FOG");
  45532. }
  45533. if (this._defines.POINTSIZE) {
  45534. fallbacks.addFallback(0, "POINTSIZE");
  45535. }
  45536. if (this._defines.LOGARITHMICDEPTH) {
  45537. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  45538. }
  45539. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  45540. if (this._defines.SPECULARTERM) {
  45541. fallbacks.addFallback(0, "SPECULARTERM");
  45542. }
  45543. if (this._defines.OPACITYFRESNEL) {
  45544. fallbacks.addFallback(1, "OPACITYFRESNEL");
  45545. }
  45546. if (this._defines.EMISSIVEFRESNEL) {
  45547. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  45548. }
  45549. if (this._defines.FRESNEL) {
  45550. fallbacks.addFallback(3, "FRESNEL");
  45551. }
  45552. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  45553. fallbacks.addCPUSkinningFallback(0, mesh);
  45554. }
  45555. //Attributes
  45556. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45557. if (this._defines.NORMAL) {
  45558. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45559. }
  45560. if (this._defines.UV1) {
  45561. attribs.push(BABYLON.VertexBuffer.UVKind);
  45562. }
  45563. if (this._defines.UV2) {
  45564. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45565. }
  45566. if (this._defines.VERTEXCOLOR) {
  45567. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45568. }
  45569. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  45570. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  45571. // Legacy browser patch
  45572. var shaderName = "pbr";
  45573. if (!scene.getEngine().getCaps().standardDerivatives) {
  45574. shaderName = "legacypbr";
  45575. }
  45576. var join = this._defines.toString();
  45577. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45578. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  45579. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  45580. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  45581. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  45582. "vFogInfos", "vFogColor", "pointSize",
  45583. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45584. "mBones",
  45585. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45586. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  45587. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  45588. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  45589. "logarithmicDepthConstant",
  45590. "vSphericalX", "vSphericalY", "vSphericalZ",
  45591. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45592. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45593. "vMicrosurfaceTextureLods", "vLightRadiuses"
  45594. ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  45595. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  45596. ], join, fallbacks, this.onCompiled, this.onError);
  45597. }
  45598. if (!this._effect.isReady()) {
  45599. return false;
  45600. }
  45601. this._renderId = scene.getRenderId();
  45602. this._wasPreviouslyReady = true;
  45603. if (mesh) {
  45604. if (!mesh._materialDefines) {
  45605. mesh._materialDefines = new PBRMaterialDefines();
  45606. }
  45607. this._defines.cloneTo(mesh._materialDefines);
  45608. }
  45609. return true;
  45610. };
  45611. PBRMaterial.prototype.unbind = function () {
  45612. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  45613. this._effect.setTexture("reflection2DSampler", null);
  45614. }
  45615. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  45616. this._effect.setTexture("refraction2DSampler", null);
  45617. }
  45618. _super.prototype.unbind.call(this);
  45619. };
  45620. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  45621. this._effect.setMatrix("world", world);
  45622. };
  45623. PBRMaterial.prototype.bind = function (world, mesh) {
  45624. this._myScene = this.getScene();
  45625. // Matrices
  45626. this.bindOnlyWorldMatrix(world);
  45627. // Bones
  45628. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  45629. if (this._myScene.getCachedMaterial() !== this) {
  45630. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  45631. if (BABYLON.StandardMaterial.FresnelEnabled) {
  45632. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  45633. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  45634. }
  45635. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  45636. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  45637. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  45638. }
  45639. }
  45640. // Textures
  45641. if (this._myScene.texturesEnabled) {
  45642. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45643. this._effect.setTexture("albedoSampler", this.albedoTexture);
  45644. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  45645. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  45646. }
  45647. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45648. this._effect.setTexture("ambientSampler", this.ambientTexture);
  45649. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  45650. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  45651. }
  45652. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45653. this._effect.setTexture("opacitySampler", this.opacityTexture);
  45654. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  45655. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  45656. }
  45657. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45658. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  45659. if (this.reflectionTexture.isCube) {
  45660. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  45661. }
  45662. else {
  45663. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  45664. }
  45665. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  45666. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  45667. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  45668. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  45669. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  45670. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  45671. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  45672. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  45673. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  45674. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  45675. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  45676. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  45677. }
  45678. }
  45679. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45680. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  45681. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  45682. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  45683. }
  45684. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45685. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  45686. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  45687. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  45688. }
  45689. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45690. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  45691. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  45692. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  45693. }
  45694. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  45695. this._effect.setTexture("bumpSampler", this.bumpTexture);
  45696. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  45697. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  45698. }
  45699. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45700. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  45701. var depth = 1.0;
  45702. if (this.refractionTexture.isCube) {
  45703. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  45704. }
  45705. else {
  45706. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  45707. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  45708. if (this.refractionTexture.depth) {
  45709. depth = this.refractionTexture.depth;
  45710. }
  45711. }
  45712. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  45713. }
  45714. if ((this.reflectionTexture || this.refractionTexture)) {
  45715. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  45716. }
  45717. }
  45718. // Clip plane
  45719. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  45720. // Point size
  45721. if (this.pointsCloud) {
  45722. this._effect.setFloat("pointSize", this.pointSize);
  45723. }
  45724. // Colors
  45725. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  45726. // GAMMA CORRECTION.
  45727. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  45728. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  45729. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45730. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  45731. // GAMMA CORRECTION.
  45732. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  45733. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  45734. // GAMMA CORRECTION.
  45735. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  45736. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  45737. }
  45738. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  45739. // GAMMA CORRECTION.
  45740. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  45741. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  45742. // Lights
  45743. if (this._myScene.lightsEnabled && !this.disableLighting) {
  45744. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace);
  45745. }
  45746. // View
  45747. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  45748. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  45749. }
  45750. // Fog
  45751. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  45752. this._lightingInfos.x = this.directIntensity;
  45753. this._lightingInfos.y = this.emissiveIntensity;
  45754. this._lightingInfos.z = this.environmentIntensity;
  45755. this._lightingInfos.w = this.specularIntensity;
  45756. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  45757. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  45758. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  45759. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  45760. this._cameraInfos.x = this.cameraExposure;
  45761. this._cameraInfos.y = this.cameraContrast;
  45762. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  45763. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  45764. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  45765. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  45766. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  45767. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  45768. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  45769. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  45770. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  45771. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  45772. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  45773. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  45774. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  45775. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  45776. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  45777. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  45778. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  45779. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  45780. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  45781. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  45782. // Log. depth
  45783. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  45784. }
  45785. _super.prototype.bind.call(this, world, mesh);
  45786. this._myScene = null;
  45787. };
  45788. PBRMaterial.prototype.getAnimatables = function () {
  45789. var results = [];
  45790. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  45791. results.push(this.albedoTexture);
  45792. }
  45793. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  45794. results.push(this.ambientTexture);
  45795. }
  45796. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  45797. results.push(this.opacityTexture);
  45798. }
  45799. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  45800. results.push(this.reflectionTexture);
  45801. }
  45802. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  45803. results.push(this.emissiveTexture);
  45804. }
  45805. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  45806. results.push(this.reflectivityTexture);
  45807. }
  45808. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  45809. results.push(this.bumpTexture);
  45810. }
  45811. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  45812. results.push(this.lightmapTexture);
  45813. }
  45814. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  45815. results.push(this.refractionTexture);
  45816. }
  45817. return results;
  45818. };
  45819. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45820. if (forceDisposeTextures) {
  45821. if (this.albedoTexture) {
  45822. this.albedoTexture.dispose();
  45823. }
  45824. if (this.ambientTexture) {
  45825. this.ambientTexture.dispose();
  45826. }
  45827. if (this.opacityTexture) {
  45828. this.opacityTexture.dispose();
  45829. }
  45830. if (this.reflectionTexture) {
  45831. this.reflectionTexture.dispose();
  45832. }
  45833. if (this.emissiveTexture) {
  45834. this.emissiveTexture.dispose();
  45835. }
  45836. if (this.reflectivityTexture) {
  45837. this.reflectivityTexture.dispose();
  45838. }
  45839. if (this.bumpTexture) {
  45840. this.bumpTexture.dispose();
  45841. }
  45842. if (this.lightmapTexture) {
  45843. this.lightmapTexture.dispose();
  45844. }
  45845. if (this.refractionTexture) {
  45846. this.refractionTexture.dispose();
  45847. }
  45848. }
  45849. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45850. };
  45851. PBRMaterial.prototype.clone = function (name) {
  45852. var _this = this;
  45853. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45854. };
  45855. PBRMaterial.prototype.serialize = function () {
  45856. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45857. serializationObject.customType = "BABYLON.PBRMaterial";
  45858. return serializationObject;
  45859. };
  45860. // Statics
  45861. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45862. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45863. };
  45864. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  45865. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  45866. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  45867. PBRMaterial._scaledReflection = new BABYLON.Color3();
  45868. PBRMaterial._lightRadiuses = [1, 1, 1, 1];
  45869. __decorate([
  45870. BABYLON.serialize()
  45871. ], PBRMaterial.prototype, "directIntensity", void 0);
  45872. __decorate([
  45873. BABYLON.serialize()
  45874. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45875. __decorate([
  45876. BABYLON.serialize()
  45877. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45878. __decorate([
  45879. BABYLON.serialize()
  45880. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45881. __decorate([
  45882. BABYLON.serialize()
  45883. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45884. __decorate([
  45885. BABYLON.serialize()
  45886. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  45887. __decorate([
  45888. BABYLON.serialize()
  45889. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  45890. __decorate([
  45891. BABYLON.serialize()
  45892. ], PBRMaterial.prototype, "cameraExposure", void 0);
  45893. __decorate([
  45894. BABYLON.serialize()
  45895. ], PBRMaterial.prototype, "cameraContrast", void 0);
  45896. __decorate([
  45897. BABYLON.serializeAsColor3()
  45898. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  45899. __decorate([
  45900. BABYLON.serialize()
  45901. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  45902. __decorate([
  45903. BABYLON.serializeAsColor3()
  45904. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  45905. __decorate([
  45906. BABYLON.serialize()
  45907. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  45908. __decorate([
  45909. BABYLON.serializeAsColor3()
  45910. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  45911. __decorate([
  45912. BABYLON.serialize()
  45913. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  45914. __decorate([
  45915. BABYLON.serializeAsColor3()
  45916. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  45917. __decorate([
  45918. BABYLON.serialize()
  45919. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  45920. __decorate([
  45921. BABYLON.serializeAsColor3()
  45922. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  45923. __decorate([
  45924. BABYLON.serialize()
  45925. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  45926. __decorate([
  45927. BABYLON.serialize()
  45928. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  45929. __decorate([
  45930. BABYLON.serialize()
  45931. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  45932. __decorate([
  45933. BABYLON.serializeAsTexture()
  45934. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45935. __decorate([
  45936. BABYLON.serializeAsTexture()
  45937. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45938. __decorate([
  45939. BABYLON.serializeAsTexture()
  45940. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45941. __decorate([
  45942. BABYLON.serializeAsTexture()
  45943. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45944. __decorate([
  45945. BABYLON.serializeAsTexture()
  45946. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45947. __decorate([
  45948. BABYLON.serializeAsTexture()
  45949. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45950. __decorate([
  45951. BABYLON.serializeAsTexture()
  45952. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45953. __decorate([
  45954. BABYLON.serializeAsTexture()
  45955. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45956. __decorate([
  45957. BABYLON.serializeAsTexture()
  45958. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45959. __decorate([
  45960. BABYLON.serializeAsColor3("ambient")
  45961. ], PBRMaterial.prototype, "ambientColor", void 0);
  45962. __decorate([
  45963. BABYLON.serializeAsColor3("albedo")
  45964. ], PBRMaterial.prototype, "albedoColor", void 0);
  45965. __decorate([
  45966. BABYLON.serializeAsColor3("reflectivity")
  45967. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45968. __decorate([
  45969. BABYLON.serializeAsColor3("reflection")
  45970. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45971. __decorate([
  45972. BABYLON.serializeAsColor3("emissive")
  45973. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45974. __decorate([
  45975. BABYLON.serialize()
  45976. ], PBRMaterial.prototype, "microSurface", void 0);
  45977. __decorate([
  45978. BABYLON.serialize()
  45979. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45980. __decorate([
  45981. BABYLON.serialize()
  45982. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45983. __decorate([
  45984. BABYLON.serializeAsFresnelParameters()
  45985. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  45986. __decorate([
  45987. BABYLON.serializeAsFresnelParameters()
  45988. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  45989. __decorate([
  45990. BABYLON.serialize()
  45991. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45992. __decorate([
  45993. BABYLON.serialize()
  45994. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  45995. __decorate([
  45996. BABYLON.serialize()
  45997. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45998. __decorate([
  45999. BABYLON.serialize()
  46000. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  46001. __decorate([
  46002. BABYLON.serialize()
  46003. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46004. __decorate([
  46005. BABYLON.serialize()
  46006. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46007. __decorate([
  46008. BABYLON.serialize()
  46009. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46010. __decorate([
  46011. BABYLON.serialize()
  46012. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46013. __decorate([
  46014. BABYLON.serialize()
  46015. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  46016. __decorate([
  46017. BABYLON.serialize()
  46018. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46019. __decorate([
  46020. BABYLON.serialize()
  46021. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46022. __decorate([
  46023. BABYLON.serialize()
  46024. ], PBRMaterial.prototype, "useParallax", void 0);
  46025. __decorate([
  46026. BABYLON.serialize()
  46027. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46028. __decorate([
  46029. BABYLON.serialize()
  46030. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46031. __decorate([
  46032. BABYLON.serialize()
  46033. ], PBRMaterial.prototype, "disableLighting", void 0);
  46034. __decorate([
  46035. BABYLON.serialize()
  46036. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  46037. return PBRMaterial;
  46038. })(BABYLON.Material);
  46039. BABYLON.PBRMaterial = PBRMaterial;
  46040. })(BABYLON || (BABYLON = {}));
  46041. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vLightRadiuses;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightRadiuses;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0 ,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0 ,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  46042. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,vec3(1.,1.,1.));\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\nfloat computeLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\nreturn lightDistanceFalloff;\n#else\nfloat lightFalloff=max(0.,1.0-length(lightOffset)/range);\nreturn lightFalloff;\n#endif\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeLightFalloff(lightOffset,lightDistanceSquared,range);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(lightOffset);\n\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeLightFalloff(lightOffset,lightDistanceSquared,range);\n\nattenuation*=cosAngle;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
  46043. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4],o=t.x*i.m[1]+t.y*i.m[5];return new n(r,o)},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new h(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,u=o.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=c.X,m=c.Y,y=0,p=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=_.Vector3[0],T=0,R=_.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var M=_.Vector3[2],F=_.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),M.x=l,M.y=x,M.z=z,M.normalize(),n.CrossToRef(M,R,F),F.normalize(),n.CrossToRef(a,M,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,M),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,n.Dot(F,m)<0&&(p=Math.PI+p,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=p,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new s(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=s.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=h;var a=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new s(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*F+s*P+e*I,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*F+u*P+m*I,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*F+p*P+f*I,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*F+z*P+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return h.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(0>t||t>3)return null;var i=4*t;return new e(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(0>t||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),\nn},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){h.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){var o=new s(0,0,0),e=new h,a=new s(0,0,0);i.decompose(o,e,a);var u=new s(0,0,0),m=new h,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=h.Slerp(e,m,r),f=s.Lerp(a,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new h,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=a;var u=function(){function t(t,i,n,r){this.normal=new s(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=a.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return s.Dot(n,i)+r},t}();t.Plane=u;var m=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=m;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new u(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=c;var p=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new x(e,h,a),m=u.angle.radians()/s;u.orientation===f.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,l=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,l),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=z;var w=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=w;var v=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=v;var d=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=d;var g=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=g;var T=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var R=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=R;var _=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new h(0,0,0,0)],t.Matrix=[a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero()],t}();t.Tmp=_}(BABYLON||(BABYLON={}));";
  46044. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  46045. module.exports = BABYLON;
  46046. };