babylon.max.js 2.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. BABYLON.ToGammaSpace = 1 / 2.2;
  10. BABYLON.ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. 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);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Tmp.Vector3[0];
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.conjugateToRef = function (ref) {
  1295. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1296. return this;
  1297. };
  1298. Quaternion.prototype.conjugateInPlace = function () {
  1299. this.x *= -1;
  1300. this.y *= -1;
  1301. this.z *= -1;
  1302. return this;
  1303. };
  1304. Quaternion.prototype.conjugate = function () {
  1305. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1306. return result;
  1307. };
  1308. Quaternion.prototype.length = function () {
  1309. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1310. };
  1311. Quaternion.prototype.normalize = function () {
  1312. var length = 1.0 / this.length();
  1313. this.x *= length;
  1314. this.y *= length;
  1315. this.z *= length;
  1316. this.w *= length;
  1317. return this;
  1318. };
  1319. Quaternion.prototype.toEulerAngles = function (order) {
  1320. if (order === void 0) { order = "YZX"; }
  1321. var result = Vector3.Zero();
  1322. this.toEulerAnglesToRef(result, order);
  1323. return result;
  1324. };
  1325. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1326. if (order === void 0) { order = "YZX"; }
  1327. var heading, attitude, bank;
  1328. var x = this.x, y = this.y, z = this.z, w = this.w;
  1329. switch (order) {
  1330. case "YZX":
  1331. var test = x * y + z * w;
  1332. if (test > 0.499) {
  1333. heading = 2 * Math.atan2(x, w);
  1334. attitude = Math.PI / 2;
  1335. bank = 0;
  1336. }
  1337. if (test < -0.499) {
  1338. heading = -2 * Math.atan2(x, w);
  1339. attitude = -Math.PI / 2;
  1340. bank = 0;
  1341. }
  1342. if (isNaN(heading)) {
  1343. var sqx = x * x;
  1344. var sqy = y * y;
  1345. var sqz = z * z;
  1346. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1347. attitude = Math.asin(2 * test); // attitude
  1348. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1349. }
  1350. break;
  1351. default:
  1352. throw new Error("Euler order " + order + " not supported yet.");
  1353. }
  1354. result.y = heading;
  1355. result.z = attitude;
  1356. result.x = bank;
  1357. return this;
  1358. };
  1359. ;
  1360. Quaternion.prototype.toRotationMatrix = function (result) {
  1361. var xx = this.x * this.x;
  1362. var yy = this.y * this.y;
  1363. var zz = this.z * this.z;
  1364. var xy = this.x * this.y;
  1365. var zw = this.z * this.w;
  1366. var zx = this.z * this.x;
  1367. var yw = this.y * this.w;
  1368. var yz = this.y * this.z;
  1369. var xw = this.x * this.w;
  1370. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1371. result.m[1] = 2.0 * (xy + zw);
  1372. result.m[2] = 2.0 * (zx - yw);
  1373. result.m[3] = 0;
  1374. result.m[4] = 2.0 * (xy - zw);
  1375. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1376. result.m[6] = 2.0 * (yz + xw);
  1377. result.m[7] = 0;
  1378. result.m[8] = 2.0 * (zx + yw);
  1379. result.m[9] = 2.0 * (yz - xw);
  1380. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1381. result.m[11] = 0;
  1382. result.m[12] = 0;
  1383. result.m[13] = 0;
  1384. result.m[14] = 0;
  1385. result.m[15] = 1.0;
  1386. return this;
  1387. };
  1388. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1389. Quaternion.FromRotationMatrixToRef(matrix, this);
  1390. return this;
  1391. };
  1392. // Statics
  1393. Quaternion.FromRotationMatrix = function (matrix) {
  1394. var result = new Quaternion();
  1395. Quaternion.FromRotationMatrixToRef(matrix, result);
  1396. return result;
  1397. };
  1398. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1399. var data = matrix.m;
  1400. var m11 = data[0], m12 = data[4], m13 = data[8];
  1401. var m21 = data[1], m22 = data[5], m23 = data[9];
  1402. var m31 = data[2], m32 = data[6], m33 = data[10];
  1403. var trace = m11 + m22 + m33;
  1404. var s;
  1405. if (trace > 0) {
  1406. s = 0.5 / Math.sqrt(trace + 1.0);
  1407. result.w = 0.25 / s;
  1408. result.x = (m32 - m23) * s;
  1409. result.y = (m13 - m31) * s;
  1410. result.z = (m21 - m12) * s;
  1411. }
  1412. else if (m11 > m22 && m11 > m33) {
  1413. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1414. result.w = (m32 - m23) / s;
  1415. result.x = 0.25 * s;
  1416. result.y = (m12 + m21) / s;
  1417. result.z = (m13 + m31) / s;
  1418. }
  1419. else if (m22 > m33) {
  1420. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1421. result.w = (m13 - m31) / s;
  1422. result.x = (m12 + m21) / s;
  1423. result.y = 0.25 * s;
  1424. result.z = (m23 + m32) / s;
  1425. }
  1426. else {
  1427. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1428. result.w = (m21 - m12) / s;
  1429. result.x = (m13 + m31) / s;
  1430. result.y = (m23 + m32) / s;
  1431. result.z = 0.25 * s;
  1432. }
  1433. };
  1434. Quaternion.Inverse = function (q) {
  1435. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1436. };
  1437. Quaternion.Identity = function () {
  1438. return new Quaternion(0, 0, 0, 1);
  1439. };
  1440. Quaternion.RotationAxis = function (axis, angle) {
  1441. var result = new Quaternion();
  1442. var sin = Math.sin(angle / 2);
  1443. axis.normalize();
  1444. result.w = Math.cos(angle / 2);
  1445. result.x = axis.x * sin;
  1446. result.y = axis.y * sin;
  1447. result.z = axis.z * sin;
  1448. return result;
  1449. };
  1450. Quaternion.FromArray = function (array, offset) {
  1451. if (!offset) {
  1452. offset = 0;
  1453. }
  1454. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1455. };
  1456. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1457. var result = new Quaternion();
  1458. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1459. return result;
  1460. };
  1461. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1462. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1463. var halfRoll = roll * 0.5;
  1464. var halfPitch = pitch * 0.5;
  1465. var halfYaw = yaw * 0.5;
  1466. var sinRoll = Math.sin(halfRoll);
  1467. var cosRoll = Math.cos(halfRoll);
  1468. var sinPitch = Math.sin(halfPitch);
  1469. var cosPitch = Math.cos(halfPitch);
  1470. var sinYaw = Math.sin(halfYaw);
  1471. var cosYaw = Math.cos(halfYaw);
  1472. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1473. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1474. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1475. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1476. };
  1477. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1478. var result = new Quaternion();
  1479. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1480. return result;
  1481. };
  1482. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1483. // Produces a quaternion from Euler angles in the z-x-z orientation
  1484. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1485. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1486. var halfBeta = beta * 0.5;
  1487. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1488. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1489. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1490. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1491. };
  1492. Quaternion.Slerp = function (left, right, amount) {
  1493. var num2;
  1494. var num3;
  1495. var num = amount;
  1496. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1497. var flag = false;
  1498. if (num4 < 0) {
  1499. flag = true;
  1500. num4 = -num4;
  1501. }
  1502. if (num4 > 0.999999) {
  1503. num3 = 1 - num;
  1504. num2 = flag ? -num : num;
  1505. }
  1506. else {
  1507. var num5 = Math.acos(num4);
  1508. var num6 = (1.0 / Math.sin(num5));
  1509. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1510. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1511. }
  1512. 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));
  1513. };
  1514. return Quaternion;
  1515. })();
  1516. BABYLON.Quaternion = Quaternion;
  1517. var Matrix = (function () {
  1518. function Matrix() {
  1519. this.m = new Float32Array(16);
  1520. }
  1521. // Properties
  1522. Matrix.prototype.isIdentity = function () {
  1523. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1524. return false;
  1525. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1526. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1527. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1528. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1529. return false;
  1530. return true;
  1531. };
  1532. Matrix.prototype.determinant = function () {
  1533. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1534. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1535. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1536. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1537. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1538. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1539. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1540. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1541. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1542. };
  1543. // Methods
  1544. Matrix.prototype.toArray = function () {
  1545. return this.m;
  1546. };
  1547. Matrix.prototype.asArray = function () {
  1548. return this.toArray();
  1549. };
  1550. Matrix.prototype.invert = function () {
  1551. this.invertToRef(this);
  1552. return this;
  1553. };
  1554. Matrix.prototype.reset = function () {
  1555. for (var index = 0; index < 16; index++) {
  1556. this.m[index] = 0;
  1557. }
  1558. return this;
  1559. };
  1560. Matrix.prototype.add = function (other) {
  1561. var result = new Matrix();
  1562. this.addToRef(other, result);
  1563. return result;
  1564. };
  1565. Matrix.prototype.addToRef = function (other, result) {
  1566. for (var index = 0; index < 16; index++) {
  1567. result.m[index] = this.m[index] + other.m[index];
  1568. }
  1569. return this;
  1570. };
  1571. Matrix.prototype.addToSelf = function (other) {
  1572. for (var index = 0; index < 16; index++) {
  1573. this.m[index] += other.m[index];
  1574. }
  1575. return this;
  1576. };
  1577. Matrix.prototype.invertToRef = function (other) {
  1578. var l1 = this.m[0];
  1579. var l2 = this.m[1];
  1580. var l3 = this.m[2];
  1581. var l4 = this.m[3];
  1582. var l5 = this.m[4];
  1583. var l6 = this.m[5];
  1584. var l7 = this.m[6];
  1585. var l8 = this.m[7];
  1586. var l9 = this.m[8];
  1587. var l10 = this.m[9];
  1588. var l11 = this.m[10];
  1589. var l12 = this.m[11];
  1590. var l13 = this.m[12];
  1591. var l14 = this.m[13];
  1592. var l15 = this.m[14];
  1593. var l16 = this.m[15];
  1594. var l17 = (l11 * l16) - (l12 * l15);
  1595. var l18 = (l10 * l16) - (l12 * l14);
  1596. var l19 = (l10 * l15) - (l11 * l14);
  1597. var l20 = (l9 * l16) - (l12 * l13);
  1598. var l21 = (l9 * l15) - (l11 * l13);
  1599. var l22 = (l9 * l14) - (l10 * l13);
  1600. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1601. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1602. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1603. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1604. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1605. var l28 = (l7 * l16) - (l8 * l15);
  1606. var l29 = (l6 * l16) - (l8 * l14);
  1607. var l30 = (l6 * l15) - (l7 * l14);
  1608. var l31 = (l5 * l16) - (l8 * l13);
  1609. var l32 = (l5 * l15) - (l7 * l13);
  1610. var l33 = (l5 * l14) - (l6 * l13);
  1611. var l34 = (l7 * l12) - (l8 * l11);
  1612. var l35 = (l6 * l12) - (l8 * l10);
  1613. var l36 = (l6 * l11) - (l7 * l10);
  1614. var l37 = (l5 * l12) - (l8 * l9);
  1615. var l38 = (l5 * l11) - (l7 * l9);
  1616. var l39 = (l5 * l10) - (l6 * l9);
  1617. other.m[0] = l23 * l27;
  1618. other.m[4] = l24 * l27;
  1619. other.m[8] = l25 * l27;
  1620. other.m[12] = l26 * l27;
  1621. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1622. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1623. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1624. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1625. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1626. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1627. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1628. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1629. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1630. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1631. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1632. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1633. return this;
  1634. };
  1635. Matrix.prototype.setTranslation = function (vector3) {
  1636. this.m[12] = vector3.x;
  1637. this.m[13] = vector3.y;
  1638. this.m[14] = vector3.z;
  1639. return this;
  1640. };
  1641. Matrix.prototype.multiply = function (other) {
  1642. var result = new Matrix();
  1643. this.multiplyToRef(other, result);
  1644. return result;
  1645. };
  1646. Matrix.prototype.copyFrom = function (other) {
  1647. for (var index = 0; index < 16; index++) {
  1648. this.m[index] = other.m[index];
  1649. }
  1650. return this;
  1651. };
  1652. Matrix.prototype.copyToArray = function (array, offset) {
  1653. if (offset === void 0) { offset = 0; }
  1654. for (var index = 0; index < 16; index++) {
  1655. array[offset + index] = this.m[index];
  1656. }
  1657. return this;
  1658. };
  1659. Matrix.prototype.multiplyToRef = function (other, result) {
  1660. this.multiplyToArray(other, result.m, 0);
  1661. return this;
  1662. };
  1663. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1664. var tm0 = this.m[0];
  1665. var tm1 = this.m[1];
  1666. var tm2 = this.m[2];
  1667. var tm3 = this.m[3];
  1668. var tm4 = this.m[4];
  1669. var tm5 = this.m[5];
  1670. var tm6 = this.m[6];
  1671. var tm7 = this.m[7];
  1672. var tm8 = this.m[8];
  1673. var tm9 = this.m[9];
  1674. var tm10 = this.m[10];
  1675. var tm11 = this.m[11];
  1676. var tm12 = this.m[12];
  1677. var tm13 = this.m[13];
  1678. var tm14 = this.m[14];
  1679. var tm15 = this.m[15];
  1680. var om0 = other.m[0];
  1681. var om1 = other.m[1];
  1682. var om2 = other.m[2];
  1683. var om3 = other.m[3];
  1684. var om4 = other.m[4];
  1685. var om5 = other.m[5];
  1686. var om6 = other.m[6];
  1687. var om7 = other.m[7];
  1688. var om8 = other.m[8];
  1689. var om9 = other.m[9];
  1690. var om10 = other.m[10];
  1691. var om11 = other.m[11];
  1692. var om12 = other.m[12];
  1693. var om13 = other.m[13];
  1694. var om14 = other.m[14];
  1695. var om15 = other.m[15];
  1696. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1697. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1698. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1699. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1700. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1701. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1702. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1703. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1704. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1705. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1706. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1707. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1708. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1709. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1710. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1711. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1712. return this;
  1713. };
  1714. Matrix.prototype.equals = function (value) {
  1715. return value &&
  1716. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1717. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1718. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1719. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1720. };
  1721. Matrix.prototype.clone = function () {
  1722. 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]);
  1723. };
  1724. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1725. translation.x = this.m[12];
  1726. translation.y = this.m[13];
  1727. translation.z = this.m[14];
  1728. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1729. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1730. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1731. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1732. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1733. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1734. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1735. rotation.x = 0;
  1736. rotation.y = 0;
  1737. rotation.z = 0;
  1738. rotation.w = 1;
  1739. return false;
  1740. }
  1741. 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);
  1742. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1743. return true;
  1744. };
  1745. // Statics
  1746. Matrix.FromArray = function (array, offset) {
  1747. var result = new Matrix();
  1748. if (!offset) {
  1749. offset = 0;
  1750. }
  1751. Matrix.FromArrayToRef(array, offset, result);
  1752. return result;
  1753. };
  1754. Matrix.FromArrayToRef = function (array, offset, result) {
  1755. for (var index = 0; index < 16; index++) {
  1756. result.m[index] = array[index + offset];
  1757. }
  1758. };
  1759. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1760. for (var index = 0; index < 16; index++) {
  1761. result.m[index] = array[index + offset] * scale;
  1762. }
  1763. };
  1764. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1765. result.m[0] = initialM11;
  1766. result.m[1] = initialM12;
  1767. result.m[2] = initialM13;
  1768. result.m[3] = initialM14;
  1769. result.m[4] = initialM21;
  1770. result.m[5] = initialM22;
  1771. result.m[6] = initialM23;
  1772. result.m[7] = initialM24;
  1773. result.m[8] = initialM31;
  1774. result.m[9] = initialM32;
  1775. result.m[10] = initialM33;
  1776. result.m[11] = initialM34;
  1777. result.m[12] = initialM41;
  1778. result.m[13] = initialM42;
  1779. result.m[14] = initialM43;
  1780. result.m[15] = initialM44;
  1781. };
  1782. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1783. var result = new Matrix();
  1784. result.m[0] = initialM11;
  1785. result.m[1] = initialM12;
  1786. result.m[2] = initialM13;
  1787. result.m[3] = initialM14;
  1788. result.m[4] = initialM21;
  1789. result.m[5] = initialM22;
  1790. result.m[6] = initialM23;
  1791. result.m[7] = initialM24;
  1792. result.m[8] = initialM31;
  1793. result.m[9] = initialM32;
  1794. result.m[10] = initialM33;
  1795. result.m[11] = initialM34;
  1796. result.m[12] = initialM41;
  1797. result.m[13] = initialM42;
  1798. result.m[14] = initialM43;
  1799. result.m[15] = initialM44;
  1800. return result;
  1801. };
  1802. Matrix.Compose = function (scale, rotation, translation) {
  1803. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1804. var rotationMatrix = Matrix.Identity();
  1805. rotation.toRotationMatrix(rotationMatrix);
  1806. result = result.multiply(rotationMatrix);
  1807. result.setTranslation(translation);
  1808. return result;
  1809. };
  1810. Matrix.Identity = function () {
  1811. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1812. };
  1813. Matrix.IdentityToRef = function (result) {
  1814. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1815. };
  1816. Matrix.Zero = function () {
  1817. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1818. };
  1819. Matrix.RotationX = function (angle) {
  1820. var result = new Matrix();
  1821. Matrix.RotationXToRef(angle, result);
  1822. return result;
  1823. };
  1824. Matrix.Invert = function (source) {
  1825. var result = new Matrix();
  1826. source.invertToRef(result);
  1827. return result;
  1828. };
  1829. Matrix.RotationXToRef = function (angle, result) {
  1830. var s = Math.sin(angle);
  1831. var c = Math.cos(angle);
  1832. result.m[0] = 1.0;
  1833. result.m[15] = 1.0;
  1834. result.m[5] = c;
  1835. result.m[10] = c;
  1836. result.m[9] = -s;
  1837. result.m[6] = s;
  1838. result.m[1] = 0;
  1839. result.m[2] = 0;
  1840. result.m[3] = 0;
  1841. result.m[4] = 0;
  1842. result.m[7] = 0;
  1843. result.m[8] = 0;
  1844. result.m[11] = 0;
  1845. result.m[12] = 0;
  1846. result.m[13] = 0;
  1847. result.m[14] = 0;
  1848. };
  1849. Matrix.RotationY = function (angle) {
  1850. var result = new Matrix();
  1851. Matrix.RotationYToRef(angle, result);
  1852. return result;
  1853. };
  1854. Matrix.RotationYToRef = function (angle, result) {
  1855. var s = Math.sin(angle);
  1856. var c = Math.cos(angle);
  1857. result.m[5] = 1.0;
  1858. result.m[15] = 1.0;
  1859. result.m[0] = c;
  1860. result.m[2] = -s;
  1861. result.m[8] = s;
  1862. result.m[10] = c;
  1863. result.m[1] = 0;
  1864. result.m[3] = 0;
  1865. result.m[4] = 0;
  1866. result.m[6] = 0;
  1867. result.m[7] = 0;
  1868. result.m[9] = 0;
  1869. result.m[11] = 0;
  1870. result.m[12] = 0;
  1871. result.m[13] = 0;
  1872. result.m[14] = 0;
  1873. };
  1874. Matrix.RotationZ = function (angle) {
  1875. var result = new Matrix();
  1876. Matrix.RotationZToRef(angle, result);
  1877. return result;
  1878. };
  1879. Matrix.RotationZToRef = function (angle, result) {
  1880. var s = Math.sin(angle);
  1881. var c = Math.cos(angle);
  1882. result.m[10] = 1.0;
  1883. result.m[15] = 1.0;
  1884. result.m[0] = c;
  1885. result.m[1] = s;
  1886. result.m[4] = -s;
  1887. result.m[5] = c;
  1888. result.m[2] = 0;
  1889. result.m[3] = 0;
  1890. result.m[6] = 0;
  1891. result.m[7] = 0;
  1892. result.m[8] = 0;
  1893. result.m[9] = 0;
  1894. result.m[11] = 0;
  1895. result.m[12] = 0;
  1896. result.m[13] = 0;
  1897. result.m[14] = 0;
  1898. };
  1899. Matrix.RotationAxis = function (axis, angle) {
  1900. var result = Matrix.Zero();
  1901. Matrix.RotationAxisToRef(axis, angle, result);
  1902. return result;
  1903. };
  1904. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1905. var s = Math.sin(-angle);
  1906. var c = Math.cos(-angle);
  1907. var c1 = 1 - c;
  1908. axis.normalize();
  1909. result.m[0] = (axis.x * axis.x) * c1 + c;
  1910. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1911. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1912. result.m[3] = 0.0;
  1913. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1914. result.m[5] = (axis.y * axis.y) * c1 + c;
  1915. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1916. result.m[7] = 0.0;
  1917. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1918. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1919. result.m[10] = (axis.z * axis.z) * c1 + c;
  1920. result.m[11] = 0.0;
  1921. result.m[15] = 1.0;
  1922. };
  1923. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1924. var result = new Matrix();
  1925. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1926. return result;
  1927. };
  1928. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1929. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1930. this._tempQuaternion.toRotationMatrix(result);
  1931. };
  1932. Matrix.Scaling = function (x, y, z) {
  1933. var result = Matrix.Zero();
  1934. Matrix.ScalingToRef(x, y, z, result);
  1935. return result;
  1936. };
  1937. Matrix.ScalingToRef = function (x, y, z, result) {
  1938. result.m[0] = x;
  1939. result.m[1] = 0;
  1940. result.m[2] = 0;
  1941. result.m[3] = 0;
  1942. result.m[4] = 0;
  1943. result.m[5] = y;
  1944. result.m[6] = 0;
  1945. result.m[7] = 0;
  1946. result.m[8] = 0;
  1947. result.m[9] = 0;
  1948. result.m[10] = z;
  1949. result.m[11] = 0;
  1950. result.m[12] = 0;
  1951. result.m[13] = 0;
  1952. result.m[14] = 0;
  1953. result.m[15] = 1.0;
  1954. };
  1955. Matrix.Translation = function (x, y, z) {
  1956. var result = Matrix.Identity();
  1957. Matrix.TranslationToRef(x, y, z, result);
  1958. return result;
  1959. };
  1960. Matrix.TranslationToRef = function (x, y, z, result) {
  1961. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1962. };
  1963. Matrix.Lerp = function (startValue, endValue, gradient) {
  1964. var startScale = new Vector3(0, 0, 0);
  1965. var startRotation = new Quaternion();
  1966. var startTranslation = new Vector3(0, 0, 0);
  1967. startValue.decompose(startScale, startRotation, startTranslation);
  1968. var endScale = new Vector3(0, 0, 0);
  1969. var endRotation = new Quaternion();
  1970. var endTranslation = new Vector3(0, 0, 0);
  1971. endValue.decompose(endScale, endRotation, endTranslation);
  1972. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1973. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1974. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1975. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1976. };
  1977. Matrix.LookAtLH = function (eye, target, up) {
  1978. var result = Matrix.Zero();
  1979. Matrix.LookAtLHToRef(eye, target, up, result);
  1980. return result;
  1981. };
  1982. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1983. // Z axis
  1984. target.subtractToRef(eye, this._zAxis);
  1985. this._zAxis.normalize();
  1986. // X axis
  1987. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1988. if (this._xAxis.lengthSquared() === 0) {
  1989. this._xAxis.x = 1.0;
  1990. }
  1991. else {
  1992. this._xAxis.normalize();
  1993. }
  1994. // Y axis
  1995. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1996. this._yAxis.normalize();
  1997. // Eye angles
  1998. var ex = -Vector3.Dot(this._xAxis, eye);
  1999. var ey = -Vector3.Dot(this._yAxis, eye);
  2000. var ez = -Vector3.Dot(this._zAxis, eye);
  2001. 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);
  2002. };
  2003. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2004. var matrix = Matrix.Zero();
  2005. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2006. return matrix;
  2007. };
  2008. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2009. var hw = 2.0 / width;
  2010. var hh = 2.0 / height;
  2011. var id = 1.0 / (zfar - znear);
  2012. var nid = znear / (znear - zfar);
  2013. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2014. };
  2015. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2016. var matrix = Matrix.Zero();
  2017. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2018. return matrix;
  2019. };
  2020. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2021. result.m[0] = 2.0 / (right - left);
  2022. result.m[1] = result.m[2] = result.m[3] = 0;
  2023. result.m[5] = 2.0 / (top - bottom);
  2024. result.m[4] = result.m[6] = result.m[7] = 0;
  2025. result.m[10] = -1.0 / (znear - zfar);
  2026. result.m[8] = result.m[9] = result.m[11] = 0;
  2027. result.m[12] = (left + right) / (left - right);
  2028. result.m[13] = (top + bottom) / (bottom - top);
  2029. result.m[14] = znear / (znear - zfar);
  2030. result.m[15] = 1.0;
  2031. };
  2032. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2033. var matrix = Matrix.Zero();
  2034. matrix.m[0] = (2.0 * znear) / width;
  2035. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2036. matrix.m[5] = (2.0 * znear) / height;
  2037. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2038. matrix.m[10] = -zfar / (znear - zfar);
  2039. matrix.m[8] = matrix.m[9] = 0.0;
  2040. matrix.m[11] = 1.0;
  2041. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2042. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2043. return matrix;
  2044. };
  2045. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2046. var matrix = Matrix.Zero();
  2047. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2048. return matrix;
  2049. };
  2050. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2051. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2052. var tan = 1.0 / (Math.tan(fov * 0.5));
  2053. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2054. if (v_fixed) {
  2055. result.m[0] = tan / aspect;
  2056. }
  2057. else {
  2058. result.m[0] = tan;
  2059. }
  2060. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2061. if (v_fixed) {
  2062. result.m[5] = tan;
  2063. }
  2064. else {
  2065. result.m[5] = tan * aspect;
  2066. }
  2067. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2068. result.m[8] = result.m[9] = 0.0;
  2069. result.m[10] = -zfar / (znear - zfar);
  2070. result.m[11] = 1.0;
  2071. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2072. result.m[14] = (znear * zfar) / (znear - zfar);
  2073. };
  2074. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2075. var cw = viewport.width;
  2076. var ch = viewport.height;
  2077. var cx = viewport.x;
  2078. var cy = viewport.y;
  2079. 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);
  2080. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2081. };
  2082. Matrix.GetAsMatrix2x2 = function (matrix) {
  2083. return new Float32Array([
  2084. matrix.m[0], matrix.m[1],
  2085. matrix.m[4], matrix.m[5]
  2086. ]);
  2087. };
  2088. Matrix.GetAsMatrix3x3 = function (matrix) {
  2089. return new Float32Array([
  2090. matrix.m[0], matrix.m[1], matrix.m[2],
  2091. matrix.m[4], matrix.m[5], matrix.m[6],
  2092. matrix.m[8], matrix.m[9], matrix.m[10]
  2093. ]);
  2094. };
  2095. Matrix.Transpose = function (matrix) {
  2096. var result = new Matrix();
  2097. result.m[0] = matrix.m[0];
  2098. result.m[1] = matrix.m[4];
  2099. result.m[2] = matrix.m[8];
  2100. result.m[3] = matrix.m[12];
  2101. result.m[4] = matrix.m[1];
  2102. result.m[5] = matrix.m[5];
  2103. result.m[6] = matrix.m[9];
  2104. result.m[7] = matrix.m[13];
  2105. result.m[8] = matrix.m[2];
  2106. result.m[9] = matrix.m[6];
  2107. result.m[10] = matrix.m[10];
  2108. result.m[11] = matrix.m[14];
  2109. result.m[12] = matrix.m[3];
  2110. result.m[13] = matrix.m[7];
  2111. result.m[14] = matrix.m[11];
  2112. result.m[15] = matrix.m[15];
  2113. return result;
  2114. };
  2115. Matrix.Reflection = function (plane) {
  2116. var matrix = new Matrix();
  2117. Matrix.ReflectionToRef(plane, matrix);
  2118. return matrix;
  2119. };
  2120. Matrix.ReflectionToRef = function (plane, result) {
  2121. plane.normalize();
  2122. var x = plane.normal.x;
  2123. var y = plane.normal.y;
  2124. var z = plane.normal.z;
  2125. var temp = -2 * x;
  2126. var temp2 = -2 * y;
  2127. var temp3 = -2 * z;
  2128. result.m[0] = (temp * x) + 1;
  2129. result.m[1] = temp2 * x;
  2130. result.m[2] = temp3 * x;
  2131. result.m[3] = 0.0;
  2132. result.m[4] = temp * y;
  2133. result.m[5] = (temp2 * y) + 1;
  2134. result.m[6] = temp3 * y;
  2135. result.m[7] = 0.0;
  2136. result.m[8] = temp * z;
  2137. result.m[9] = temp2 * z;
  2138. result.m[10] = (temp3 * z) + 1;
  2139. result.m[11] = 0.0;
  2140. result.m[12] = temp * plane.d;
  2141. result.m[13] = temp2 * plane.d;
  2142. result.m[14] = temp3 * plane.d;
  2143. result.m[15] = 1.0;
  2144. };
  2145. Matrix._tempQuaternion = new Quaternion();
  2146. Matrix._xAxis = Vector3.Zero();
  2147. Matrix._yAxis = Vector3.Zero();
  2148. Matrix._zAxis = Vector3.Zero();
  2149. return Matrix;
  2150. })();
  2151. BABYLON.Matrix = Matrix;
  2152. var Plane = (function () {
  2153. function Plane(a, b, c, d) {
  2154. this.normal = new Vector3(a, b, c);
  2155. this.d = d;
  2156. }
  2157. Plane.prototype.asArray = function () {
  2158. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2159. };
  2160. // Methods
  2161. Plane.prototype.clone = function () {
  2162. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2163. };
  2164. Plane.prototype.normalize = function () {
  2165. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2166. var magnitude = 0;
  2167. if (norm !== 0) {
  2168. magnitude = 1.0 / norm;
  2169. }
  2170. this.normal.x *= magnitude;
  2171. this.normal.y *= magnitude;
  2172. this.normal.z *= magnitude;
  2173. this.d *= magnitude;
  2174. return this;
  2175. };
  2176. Plane.prototype.transform = function (transformation) {
  2177. var transposedMatrix = Matrix.Transpose(transformation);
  2178. var x = this.normal.x;
  2179. var y = this.normal.y;
  2180. var z = this.normal.z;
  2181. var d = this.d;
  2182. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2183. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2184. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2185. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2186. return new Plane(normalX, normalY, normalZ, finalD);
  2187. };
  2188. Plane.prototype.dotCoordinate = function (point) {
  2189. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2190. };
  2191. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2192. var x1 = point2.x - point1.x;
  2193. var y1 = point2.y - point1.y;
  2194. var z1 = point2.z - point1.z;
  2195. var x2 = point3.x - point1.x;
  2196. var y2 = point3.y - point1.y;
  2197. var z2 = point3.z - point1.z;
  2198. var yz = (y1 * z2) - (z1 * y2);
  2199. var xz = (z1 * x2) - (x1 * z2);
  2200. var xy = (x1 * y2) - (y1 * x2);
  2201. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2202. var invPyth;
  2203. if (pyth !== 0) {
  2204. invPyth = 1.0 / pyth;
  2205. }
  2206. else {
  2207. invPyth = 0;
  2208. }
  2209. this.normal.x = yz * invPyth;
  2210. this.normal.y = xz * invPyth;
  2211. this.normal.z = xy * invPyth;
  2212. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2213. return this;
  2214. };
  2215. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2216. var dot = Vector3.Dot(this.normal, direction);
  2217. return (dot <= epsilon);
  2218. };
  2219. Plane.prototype.signedDistanceTo = function (point) {
  2220. return Vector3.Dot(point, this.normal) + this.d;
  2221. };
  2222. // Statics
  2223. Plane.FromArray = function (array) {
  2224. return new Plane(array[0], array[1], array[2], array[3]);
  2225. };
  2226. Plane.FromPoints = function (point1, point2, point3) {
  2227. var result = new Plane(0, 0, 0, 0);
  2228. result.copyFromPoints(point1, point2, point3);
  2229. return result;
  2230. };
  2231. Plane.FromPositionAndNormal = function (origin, normal) {
  2232. var result = new Plane(0, 0, 0, 0);
  2233. normal.normalize();
  2234. result.normal = normal;
  2235. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2236. return result;
  2237. };
  2238. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2239. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2240. return Vector3.Dot(point, normal) + d;
  2241. };
  2242. return Plane;
  2243. })();
  2244. BABYLON.Plane = Plane;
  2245. var Viewport = (function () {
  2246. function Viewport(x, y, width, height) {
  2247. this.x = x;
  2248. this.y = y;
  2249. this.width = width;
  2250. this.height = height;
  2251. }
  2252. Viewport.prototype.toGlobal = function (engine) {
  2253. var width = engine.getRenderWidth();
  2254. var height = engine.getRenderHeight();
  2255. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2256. };
  2257. Viewport.prototype.toScreenGlobal = function (engine) {
  2258. var width = engine.getRenderWidth(true);
  2259. var height = engine.getRenderHeight(true);
  2260. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2261. };
  2262. return Viewport;
  2263. })();
  2264. BABYLON.Viewport = Viewport;
  2265. var Frustum = (function () {
  2266. function Frustum() {
  2267. }
  2268. Frustum.GetPlanes = function (transform) {
  2269. var frustumPlanes = [];
  2270. for (var index = 0; index < 6; index++) {
  2271. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2272. }
  2273. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2274. return frustumPlanes;
  2275. };
  2276. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2277. // Near
  2278. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2279. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2280. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2281. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2282. frustumPlanes[0].normalize();
  2283. // Far
  2284. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2285. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2286. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2287. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2288. frustumPlanes[1].normalize();
  2289. // Left
  2290. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2291. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2292. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2293. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2294. frustumPlanes[2].normalize();
  2295. // Right
  2296. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2297. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2298. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2299. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2300. frustumPlanes[3].normalize();
  2301. // Top
  2302. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2303. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2304. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2305. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2306. frustumPlanes[4].normalize();
  2307. // Bottom
  2308. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2309. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2310. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2311. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2312. frustumPlanes[5].normalize();
  2313. };
  2314. return Frustum;
  2315. })();
  2316. BABYLON.Frustum = Frustum;
  2317. var Ray = (function () {
  2318. function Ray(origin, direction, length) {
  2319. if (length === void 0) { length = Number.MAX_VALUE; }
  2320. this.origin = origin;
  2321. this.direction = direction;
  2322. this.length = length;
  2323. }
  2324. // Methods
  2325. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2326. var d = 0.0;
  2327. var maxValue = Number.MAX_VALUE;
  2328. var inv;
  2329. var min;
  2330. var max;
  2331. var temp;
  2332. if (Math.abs(this.direction.x) < 0.0000001) {
  2333. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2334. return false;
  2335. }
  2336. }
  2337. else {
  2338. inv = 1.0 / this.direction.x;
  2339. min = (minimum.x - this.origin.x) * inv;
  2340. max = (maximum.x - this.origin.x) * inv;
  2341. if (max === -Infinity) {
  2342. max = Infinity;
  2343. }
  2344. if (min > max) {
  2345. temp = min;
  2346. min = max;
  2347. max = temp;
  2348. }
  2349. d = Math.max(min, d);
  2350. maxValue = Math.min(max, maxValue);
  2351. if (d > maxValue) {
  2352. return false;
  2353. }
  2354. }
  2355. if (Math.abs(this.direction.y) < 0.0000001) {
  2356. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2357. return false;
  2358. }
  2359. }
  2360. else {
  2361. inv = 1.0 / this.direction.y;
  2362. min = (minimum.y - this.origin.y) * inv;
  2363. max = (maximum.y - this.origin.y) * inv;
  2364. if (max === -Infinity) {
  2365. max = Infinity;
  2366. }
  2367. if (min > max) {
  2368. temp = min;
  2369. min = max;
  2370. max = temp;
  2371. }
  2372. d = Math.max(min, d);
  2373. maxValue = Math.min(max, maxValue);
  2374. if (d > maxValue) {
  2375. return false;
  2376. }
  2377. }
  2378. if (Math.abs(this.direction.z) < 0.0000001) {
  2379. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2380. return false;
  2381. }
  2382. }
  2383. else {
  2384. inv = 1.0 / this.direction.z;
  2385. min = (minimum.z - this.origin.z) * inv;
  2386. max = (maximum.z - this.origin.z) * inv;
  2387. if (max === -Infinity) {
  2388. max = Infinity;
  2389. }
  2390. if (min > max) {
  2391. temp = min;
  2392. min = max;
  2393. max = temp;
  2394. }
  2395. d = Math.max(min, d);
  2396. maxValue = Math.min(max, maxValue);
  2397. if (d > maxValue) {
  2398. return false;
  2399. }
  2400. }
  2401. return true;
  2402. };
  2403. Ray.prototype.intersectsBox = function (box) {
  2404. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2405. };
  2406. Ray.prototype.intersectsSphere = function (sphere) {
  2407. var x = sphere.center.x - this.origin.x;
  2408. var y = sphere.center.y - this.origin.y;
  2409. var z = sphere.center.z - this.origin.z;
  2410. var pyth = (x * x) + (y * y) + (z * z);
  2411. var rr = sphere.radius * sphere.radius;
  2412. if (pyth <= rr) {
  2413. return true;
  2414. }
  2415. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2416. if (dot < 0.0) {
  2417. return false;
  2418. }
  2419. var temp = pyth - (dot * dot);
  2420. return temp <= rr;
  2421. };
  2422. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2423. if (!this._edge1) {
  2424. this._edge1 = Vector3.Zero();
  2425. this._edge2 = Vector3.Zero();
  2426. this._pvec = Vector3.Zero();
  2427. this._tvec = Vector3.Zero();
  2428. this._qvec = Vector3.Zero();
  2429. }
  2430. vertex1.subtractToRef(vertex0, this._edge1);
  2431. vertex2.subtractToRef(vertex0, this._edge2);
  2432. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2433. var det = Vector3.Dot(this._edge1, this._pvec);
  2434. if (det === 0) {
  2435. return null;
  2436. }
  2437. var invdet = 1 / det;
  2438. this.origin.subtractToRef(vertex0, this._tvec);
  2439. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2440. if (bu < 0 || bu > 1.0) {
  2441. return null;
  2442. }
  2443. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2444. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2445. if (bv < 0 || bu + bv > 1.0) {
  2446. return null;
  2447. }
  2448. //check if the distance is longer than the predefined length.
  2449. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2450. if (distance > this.length) {
  2451. return null;
  2452. }
  2453. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2454. };
  2455. // Statics
  2456. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2457. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2458. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2459. var direction = end.subtract(start);
  2460. direction.normalize();
  2461. return new Ray(start, direction);
  2462. };
  2463. /**
  2464. * 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
  2465. * transformed to the given world matrix.
  2466. * @param origin The origin point
  2467. * @param end The end point
  2468. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2469. */
  2470. Ray.CreateNewFromTo = function (origin, end, world) {
  2471. if (world === void 0) { world = Matrix.Identity(); }
  2472. var direction = end.subtract(origin);
  2473. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2474. direction.normalize();
  2475. return Ray.Transform(new Ray(origin, direction, length), world);
  2476. };
  2477. Ray.Transform = function (ray, matrix) {
  2478. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2479. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2480. return new Ray(newOrigin, newDirection, ray.length);
  2481. };
  2482. return Ray;
  2483. })();
  2484. BABYLON.Ray = Ray;
  2485. (function (Space) {
  2486. Space[Space["LOCAL"] = 0] = "LOCAL";
  2487. Space[Space["WORLD"] = 1] = "WORLD";
  2488. })(BABYLON.Space || (BABYLON.Space = {}));
  2489. var Space = BABYLON.Space;
  2490. var Axis = (function () {
  2491. function Axis() {
  2492. }
  2493. Axis.X = new Vector3(1, 0, 0);
  2494. Axis.Y = new Vector3(0, 1, 0);
  2495. Axis.Z = new Vector3(0, 0, 1);
  2496. return Axis;
  2497. })();
  2498. BABYLON.Axis = Axis;
  2499. ;
  2500. var BezierCurve = (function () {
  2501. function BezierCurve() {
  2502. }
  2503. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2504. // Extract X (which is equal to time here)
  2505. var f0 = 1 - 3 * x2 + 3 * x1;
  2506. var f1 = 3 * x2 - 6 * x1;
  2507. var f2 = 3 * x1;
  2508. var refinedT = t;
  2509. for (var i = 0; i < 5; i++) {
  2510. var refinedT2 = refinedT * refinedT;
  2511. var refinedT3 = refinedT2 * refinedT;
  2512. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2513. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2514. refinedT -= (x - t) * slope;
  2515. refinedT = Math.min(1, Math.max(0, refinedT));
  2516. }
  2517. // Resolve cubic bezier for the given x
  2518. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2519. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2520. Math.pow(refinedT, 3);
  2521. };
  2522. return BezierCurve;
  2523. })();
  2524. BABYLON.BezierCurve = BezierCurve;
  2525. (function (Orientation) {
  2526. Orientation[Orientation["CW"] = 0] = "CW";
  2527. Orientation[Orientation["CCW"] = 1] = "CCW";
  2528. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2529. var Orientation = BABYLON.Orientation;
  2530. var Angle = (function () {
  2531. function Angle(radians) {
  2532. var _this = this;
  2533. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2534. this.radians = function () { return _this._radians; };
  2535. this._radians = radians;
  2536. if (this._radians < 0)
  2537. this._radians += (2 * Math.PI);
  2538. }
  2539. Angle.BetweenTwoPoints = function (a, b) {
  2540. var delta = b.subtract(a);
  2541. var theta = Math.atan2(delta.y, delta.x);
  2542. return new Angle(theta);
  2543. };
  2544. Angle.FromRadians = function (radians) {
  2545. return new Angle(radians);
  2546. };
  2547. Angle.FromDegrees = function (degrees) {
  2548. return new Angle(degrees * Math.PI / 180);
  2549. };
  2550. return Angle;
  2551. })();
  2552. BABYLON.Angle = Angle;
  2553. var Arc2 = (function () {
  2554. function Arc2(startPoint, midPoint, endPoint) {
  2555. this.startPoint = startPoint;
  2556. this.midPoint = midPoint;
  2557. this.endPoint = endPoint;
  2558. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2559. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2560. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2561. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2562. 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);
  2563. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2564. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2565. var a1 = this.startAngle.degrees();
  2566. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2567. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2568. // angles correction
  2569. if (a2 - a1 > +180.0)
  2570. a2 -= 360.0;
  2571. if (a2 - a1 < -180.0)
  2572. a2 += 360.0;
  2573. if (a3 - a2 > +180.0)
  2574. a3 -= 360.0;
  2575. if (a3 - a2 < -180.0)
  2576. a3 += 360.0;
  2577. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2578. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2579. }
  2580. return Arc2;
  2581. })();
  2582. BABYLON.Arc2 = Arc2;
  2583. var PathCursor = (function () {
  2584. function PathCursor(path) {
  2585. this.path = path;
  2586. this._onchange = new Array();
  2587. this.value = 0;
  2588. this.animations = new Array();
  2589. }
  2590. PathCursor.prototype.getPoint = function () {
  2591. var point = this.path.getPointAtLengthPosition(this.value);
  2592. return new Vector3(point.x, 0, point.y);
  2593. };
  2594. PathCursor.prototype.moveAhead = function (step) {
  2595. if (step === void 0) { step = 0.002; }
  2596. this.move(step);
  2597. return this;
  2598. };
  2599. PathCursor.prototype.moveBack = function (step) {
  2600. if (step === void 0) { step = 0.002; }
  2601. this.move(-step);
  2602. return this;
  2603. };
  2604. PathCursor.prototype.move = function (step) {
  2605. if (Math.abs(step) > 1) {
  2606. throw "step size should be less than 1.";
  2607. }
  2608. this.value += step;
  2609. this.ensureLimits();
  2610. this.raiseOnChange();
  2611. return this;
  2612. };
  2613. PathCursor.prototype.ensureLimits = function () {
  2614. while (this.value > 1) {
  2615. this.value -= 1;
  2616. }
  2617. while (this.value < 0) {
  2618. this.value += 1;
  2619. }
  2620. return this;
  2621. };
  2622. // used by animation engine
  2623. PathCursor.prototype.markAsDirty = function (propertyName) {
  2624. this.ensureLimits();
  2625. this.raiseOnChange();
  2626. return this;
  2627. };
  2628. PathCursor.prototype.raiseOnChange = function () {
  2629. var _this = this;
  2630. this._onchange.forEach(function (f) { return f(_this); });
  2631. return this;
  2632. };
  2633. PathCursor.prototype.onchange = function (f) {
  2634. this._onchange.push(f);
  2635. return this;
  2636. };
  2637. return PathCursor;
  2638. })();
  2639. BABYLON.PathCursor = PathCursor;
  2640. var Path2 = (function () {
  2641. function Path2(x, y) {
  2642. this._points = new Array();
  2643. this._length = 0;
  2644. this.closed = false;
  2645. this._points.push(new Vector2(x, y));
  2646. }
  2647. Path2.prototype.addLineTo = function (x, y) {
  2648. if (closed) {
  2649. BABYLON.Tools.Error("cannot add lines to closed paths");
  2650. return this;
  2651. }
  2652. var newPoint = new Vector2(x, y);
  2653. var previousPoint = this._points[this._points.length - 1];
  2654. this._points.push(newPoint);
  2655. this._length += newPoint.subtract(previousPoint).length();
  2656. return this;
  2657. };
  2658. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2659. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2660. if (closed) {
  2661. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2662. return this;
  2663. }
  2664. var startPoint = this._points[this._points.length - 1];
  2665. var midPoint = new Vector2(midX, midY);
  2666. var endPoint = new Vector2(endX, endY);
  2667. var arc = new Arc2(startPoint, midPoint, endPoint);
  2668. var increment = arc.angle.radians() / numberOfSegments;
  2669. if (arc.orientation === Orientation.CW)
  2670. increment *= -1;
  2671. var currentAngle = arc.startAngle.radians() + increment;
  2672. for (var i = 0; i < numberOfSegments; i++) {
  2673. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2674. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2675. this.addLineTo(x, y);
  2676. currentAngle += increment;
  2677. }
  2678. return this;
  2679. };
  2680. Path2.prototype.close = function () {
  2681. this.closed = true;
  2682. return this;
  2683. };
  2684. Path2.prototype.length = function () {
  2685. var result = this._length;
  2686. if (!this.closed) {
  2687. var lastPoint = this._points[this._points.length - 1];
  2688. var firstPoint = this._points[0];
  2689. result += (firstPoint.subtract(lastPoint).length());
  2690. }
  2691. return result;
  2692. };
  2693. Path2.prototype.getPoints = function () {
  2694. return this._points;
  2695. };
  2696. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2697. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2698. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2699. return Vector2.Zero();
  2700. }
  2701. var lengthPosition = normalizedLengthPosition * this.length();
  2702. var previousOffset = 0;
  2703. for (var i = 0; i < this._points.length; i++) {
  2704. var j = (i + 1) % this._points.length;
  2705. var a = this._points[i];
  2706. var b = this._points[j];
  2707. var bToA = b.subtract(a);
  2708. var nextOffset = (bToA.length() + previousOffset);
  2709. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2710. var dir = bToA.normalize();
  2711. var localOffset = lengthPosition - previousOffset;
  2712. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2713. }
  2714. previousOffset = nextOffset;
  2715. }
  2716. BABYLON.Tools.Error("internal error");
  2717. return Vector2.Zero();
  2718. };
  2719. Path2.StartingAt = function (x, y) {
  2720. return new Path2(x, y);
  2721. };
  2722. return Path2;
  2723. })();
  2724. BABYLON.Path2 = Path2;
  2725. var Path3D = (function () {
  2726. /**
  2727. * new Path3D(path, normal, raw)
  2728. * path : an array of Vector3, the curve axis of the Path3D
  2729. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2730. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2731. */
  2732. function Path3D(path, firstNormal, raw) {
  2733. this.path = path;
  2734. this._curve = new Array();
  2735. this._distances = new Array();
  2736. this._tangents = new Array();
  2737. this._normals = new Array();
  2738. this._binormals = new Array();
  2739. for (var p = 0; p < path.length; p++) {
  2740. this._curve[p] = path[p].clone(); // hard copy
  2741. }
  2742. this._raw = raw || false;
  2743. this._compute(firstNormal);
  2744. }
  2745. Path3D.prototype.getCurve = function () {
  2746. return this._curve;
  2747. };
  2748. Path3D.prototype.getTangents = function () {
  2749. return this._tangents;
  2750. };
  2751. Path3D.prototype.getNormals = function () {
  2752. return this._normals;
  2753. };
  2754. Path3D.prototype.getBinormals = function () {
  2755. return this._binormals;
  2756. };
  2757. Path3D.prototype.getDistances = function () {
  2758. return this._distances;
  2759. };
  2760. Path3D.prototype.update = function (path, firstNormal) {
  2761. for (var p = 0; p < path.length; p++) {
  2762. this._curve[p].x = path[p].x;
  2763. this._curve[p].y = path[p].y;
  2764. this._curve[p].z = path[p].z;
  2765. }
  2766. this._compute(firstNormal);
  2767. return this;
  2768. };
  2769. // private function compute() : computes tangents, normals and binormals
  2770. Path3D.prototype._compute = function (firstNormal) {
  2771. var l = this._curve.length;
  2772. // first and last tangents
  2773. this._tangents[0] = this._getFirstNonNullVector(0);
  2774. if (!this._raw) {
  2775. this._tangents[0].normalize();
  2776. }
  2777. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2778. if (!this._raw) {
  2779. this._tangents[l - 1].normalize();
  2780. }
  2781. // normals and binormals at first point : arbitrary vector with _normalVector()
  2782. var tg0 = this._tangents[0];
  2783. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2784. this._normals[0] = pp0;
  2785. if (!this._raw) {
  2786. this._normals[0].normalize();
  2787. }
  2788. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2789. if (!this._raw) {
  2790. this._binormals[0].normalize();
  2791. }
  2792. this._distances[0] = 0;
  2793. // normals and binormals : next points
  2794. var prev; // previous vector (segment)
  2795. var cur; // current vector (segment)
  2796. var curTang; // current tangent
  2797. // previous normal
  2798. var prevBinor; // previous binormal
  2799. for (var i = 1; i < l; i++) {
  2800. // tangents
  2801. prev = this._getLastNonNullVector(i);
  2802. if (i < l - 1) {
  2803. cur = this._getFirstNonNullVector(i);
  2804. this._tangents[i] = prev.add(cur);
  2805. this._tangents[i].normalize();
  2806. }
  2807. this._distances[i] = this._distances[i - 1] + prev.length();
  2808. // normals and binormals
  2809. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2810. curTang = this._tangents[i];
  2811. prevBinor = this._binormals[i - 1];
  2812. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2813. if (!this._raw) {
  2814. this._normals[i].normalize();
  2815. }
  2816. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2817. if (!this._raw) {
  2818. this._binormals[i].normalize();
  2819. }
  2820. }
  2821. };
  2822. // private function getFirstNonNullVector(index)
  2823. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2824. Path3D.prototype._getFirstNonNullVector = function (index) {
  2825. var i = 1;
  2826. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2827. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2828. i++;
  2829. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2830. }
  2831. return nNVector;
  2832. };
  2833. // private function getLastNonNullVector(index)
  2834. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2835. Path3D.prototype._getLastNonNullVector = function (index) {
  2836. var i = 1;
  2837. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2838. while (nLVector.length() === 0 && index > i + 1) {
  2839. i++;
  2840. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2841. }
  2842. return nLVector;
  2843. };
  2844. // private function normalVector(v0, vt, va) :
  2845. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2846. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2847. Path3D.prototype._normalVector = function (v0, vt, va) {
  2848. var normal0;
  2849. if (va === undefined || va === null) {
  2850. var point;
  2851. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2852. point = new Vector3(0, -1, 0);
  2853. }
  2854. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2855. point = new Vector3(1, 0, 0);
  2856. }
  2857. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2858. point = new Vector3(0, 0, 1);
  2859. }
  2860. normal0 = Vector3.Cross(vt, point);
  2861. }
  2862. else {
  2863. normal0 = Vector3.Cross(vt, va);
  2864. Vector3.CrossToRef(normal0, vt, normal0);
  2865. }
  2866. normal0.normalize();
  2867. return normal0;
  2868. };
  2869. return Path3D;
  2870. })();
  2871. BABYLON.Path3D = Path3D;
  2872. var Curve3 = (function () {
  2873. function Curve3(points) {
  2874. this._length = 0;
  2875. this._points = points;
  2876. this._length = this._computeLength(points);
  2877. }
  2878. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2879. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2880. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2881. var bez = new Array();
  2882. var equation = function (t, val0, val1, val2) {
  2883. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2884. return res;
  2885. };
  2886. for (var i = 0; i <= nbPoints; i++) {
  2887. 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)));
  2888. }
  2889. return new Curve3(bez);
  2890. };
  2891. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2892. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2893. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2894. var bez = new Array();
  2895. var equation = function (t, val0, val1, val2, val3) {
  2896. 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;
  2897. return res;
  2898. };
  2899. for (var i = 0; i <= nbPoints; i++) {
  2900. 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)));
  2901. }
  2902. return new Curve3(bez);
  2903. };
  2904. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2905. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2906. var hermite = new Array();
  2907. var step = 1 / nbPoints;
  2908. for (var i = 0; i <= nbPoints; i++) {
  2909. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2910. }
  2911. return new Curve3(hermite);
  2912. };
  2913. Curve3.prototype.getPoints = function () {
  2914. return this._points;
  2915. };
  2916. Curve3.prototype.length = function () {
  2917. return this._length;
  2918. };
  2919. Curve3.prototype.continue = function (curve) {
  2920. var lastPoint = this._points[this._points.length - 1];
  2921. var continuedPoints = this._points.slice();
  2922. var curvePoints = curve.getPoints();
  2923. for (var i = 1; i < curvePoints.length; i++) {
  2924. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2925. }
  2926. var continuedCurve = new Curve3(continuedPoints);
  2927. return continuedCurve;
  2928. };
  2929. Curve3.prototype._computeLength = function (path) {
  2930. var l = 0;
  2931. for (var i = 1; i < path.length; i++) {
  2932. l += (path[i].subtract(path[i - 1])).length();
  2933. }
  2934. return l;
  2935. };
  2936. return Curve3;
  2937. })();
  2938. BABYLON.Curve3 = Curve3;
  2939. // SphericalHarmonics
  2940. var SphericalHarmonics = (function () {
  2941. function SphericalHarmonics() {
  2942. this.L00 = Vector3.Zero();
  2943. this.L1_1 = Vector3.Zero();
  2944. this.L10 = Vector3.Zero();
  2945. this.L11 = Vector3.Zero();
  2946. this.L2_2 = Vector3.Zero();
  2947. this.L2_1 = Vector3.Zero();
  2948. this.L20 = Vector3.Zero();
  2949. this.L21 = Vector3.Zero();
  2950. this.L22 = Vector3.Zero();
  2951. }
  2952. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2953. var colorVector = new Vector3(color.r, color.g, color.b);
  2954. var c = colorVector.scale(deltaSolidAngle);
  2955. this.L00 = this.L00.add(c.scale(0.282095));
  2956. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2957. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2958. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2959. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2960. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2961. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2962. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2963. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2964. };
  2965. SphericalHarmonics.prototype.scale = function (scale) {
  2966. this.L00 = this.L00.scale(scale);
  2967. this.L1_1 = this.L1_1.scale(scale);
  2968. this.L10 = this.L10.scale(scale);
  2969. this.L11 = this.L11.scale(scale);
  2970. this.L2_2 = this.L2_2.scale(scale);
  2971. this.L2_1 = this.L2_1.scale(scale);
  2972. this.L20 = this.L20.scale(scale);
  2973. this.L21 = this.L21.scale(scale);
  2974. this.L22 = this.L22.scale(scale);
  2975. };
  2976. return SphericalHarmonics;
  2977. })();
  2978. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2979. // SphericalPolynomial
  2980. var SphericalPolynomial = (function () {
  2981. function SphericalPolynomial() {
  2982. this.x = Vector3.Zero();
  2983. this.y = Vector3.Zero();
  2984. this.z = Vector3.Zero();
  2985. this.xx = Vector3.Zero();
  2986. this.yy = Vector3.Zero();
  2987. this.zz = Vector3.Zero();
  2988. this.xy = Vector3.Zero();
  2989. this.yz = Vector3.Zero();
  2990. this.zx = Vector3.Zero();
  2991. }
  2992. SphericalPolynomial.prototype.addAmbient = function (color) {
  2993. var colorVector = new Vector3(color.r, color.g, color.b);
  2994. this.xx = this.xx.add(colorVector);
  2995. this.yy = this.yy.add(colorVector);
  2996. this.zz = this.zz.add(colorVector);
  2997. };
  2998. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2999. var result = new SphericalPolynomial();
  3000. result.x = harmonics.L11.scale(1.02333);
  3001. result.y = harmonics.L1_1.scale(1.02333);
  3002. result.z = harmonics.L10.scale(1.02333);
  3003. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3004. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3005. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3006. result.yz = harmonics.L2_1.scale(0.858086);
  3007. result.zx = harmonics.L21.scale(0.858086);
  3008. result.xy = harmonics.L2_2.scale(0.858086);
  3009. return result;
  3010. };
  3011. return SphericalPolynomial;
  3012. })();
  3013. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3014. // Vertex formats
  3015. var PositionNormalVertex = (function () {
  3016. function PositionNormalVertex(position, normal) {
  3017. if (position === void 0) { position = Vector3.Zero(); }
  3018. if (normal === void 0) { normal = Vector3.Up(); }
  3019. this.position = position;
  3020. this.normal = normal;
  3021. }
  3022. PositionNormalVertex.prototype.clone = function () {
  3023. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3024. };
  3025. return PositionNormalVertex;
  3026. })();
  3027. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3028. var PositionNormalTextureVertex = (function () {
  3029. function PositionNormalTextureVertex(position, normal, uv) {
  3030. if (position === void 0) { position = Vector3.Zero(); }
  3031. if (normal === void 0) { normal = Vector3.Up(); }
  3032. if (uv === void 0) { uv = Vector2.Zero(); }
  3033. this.position = position;
  3034. this.normal = normal;
  3035. this.uv = uv;
  3036. }
  3037. PositionNormalTextureVertex.prototype.clone = function () {
  3038. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3039. };
  3040. return PositionNormalTextureVertex;
  3041. })();
  3042. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3043. // Temporary pre-allocated objects for engine internal use
  3044. // usage in any internal function :
  3045. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3046. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3047. var Tmp = (function () {
  3048. function Tmp() {
  3049. }
  3050. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3051. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3052. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3053. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3054. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3055. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3056. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3057. Matrix.Zero(), Matrix.Zero(),
  3058. Matrix.Zero(), Matrix.Zero(),
  3059. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3060. return Tmp;
  3061. })();
  3062. BABYLON.Tmp = Tmp;
  3063. })(BABYLON || (BABYLON = {}));
  3064. var BABYLON;
  3065. (function (BABYLON) {
  3066. function generateSerializableMember(type, sourceName) {
  3067. return function (target, propertyKey) {
  3068. if (!target.__serializableMembers) {
  3069. target.__serializableMembers = {};
  3070. }
  3071. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3072. };
  3073. }
  3074. function serialize(sourceName) {
  3075. return generateSerializableMember(0, sourceName); // value member
  3076. }
  3077. BABYLON.serialize = serialize;
  3078. function serializeAsTexture(sourceName) {
  3079. return generateSerializableMember(1, sourceName); // texture member
  3080. }
  3081. BABYLON.serializeAsTexture = serializeAsTexture;
  3082. function serializeAsColor3(sourceName) {
  3083. return generateSerializableMember(2, sourceName); // color3 member
  3084. }
  3085. BABYLON.serializeAsColor3 = serializeAsColor3;
  3086. function serializeAsFresnelParameters(sourceName) {
  3087. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3088. }
  3089. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3090. function serializeAsVector2(sourceName) {
  3091. return generateSerializableMember(4, sourceName); // vector2 member
  3092. }
  3093. BABYLON.serializeAsVector2 = serializeAsVector2;
  3094. function serializeAsVector3(sourceName) {
  3095. return generateSerializableMember(5, sourceName); // vector3 member
  3096. }
  3097. BABYLON.serializeAsVector3 = serializeAsVector3;
  3098. function serializeAsMeshReference(sourceName) {
  3099. return generateSerializableMember(6, sourceName); // mesh reference member
  3100. }
  3101. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3102. var SerializationHelper = (function () {
  3103. function SerializationHelper() {
  3104. }
  3105. SerializationHelper.Serialize = function (entity, serializationObject) {
  3106. if (!serializationObject) {
  3107. serializationObject = {};
  3108. }
  3109. // Tags
  3110. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3111. // Properties
  3112. for (var property in entity.__serializableMembers) {
  3113. var propertyDescriptor = entity.__serializableMembers[property];
  3114. var targetPropertyName = propertyDescriptor.sourceName || property;
  3115. var propertyType = propertyDescriptor.type;
  3116. var sourceProperty = entity[property];
  3117. if (sourceProperty !== undefined && sourceProperty !== null) {
  3118. switch (propertyType) {
  3119. case 0:
  3120. serializationObject[targetPropertyName] = sourceProperty;
  3121. break;
  3122. case 1:
  3123. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3124. break;
  3125. case 2:
  3126. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3127. break;
  3128. case 3:
  3129. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3130. break;
  3131. case 4:
  3132. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3133. break;
  3134. case 5:
  3135. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3136. break;
  3137. case 6:
  3138. serializationObject[targetPropertyName] = sourceProperty.id;
  3139. break;
  3140. }
  3141. }
  3142. }
  3143. return serializationObject;
  3144. };
  3145. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3146. var destination = creationFunction();
  3147. // Tags
  3148. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3149. // Properties
  3150. for (var property in destination.__serializableMembers) {
  3151. var propertyDescriptor = destination.__serializableMembers[property];
  3152. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3153. var propertyType = propertyDescriptor.type;
  3154. if (sourceProperty !== undefined && sourceProperty !== null) {
  3155. switch (propertyType) {
  3156. case 0:
  3157. destination[property] = sourceProperty;
  3158. break;
  3159. case 1:
  3160. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3161. break;
  3162. case 2:
  3163. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3164. break;
  3165. case 3:
  3166. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3167. break;
  3168. case 4:
  3169. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3170. break;
  3171. case 5:
  3172. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3173. break;
  3174. case 6:
  3175. destination[property] = scene.getLastMeshByID(sourceProperty);
  3176. break;
  3177. }
  3178. }
  3179. }
  3180. return destination;
  3181. };
  3182. SerializationHelper.Clone = function (creationFunction, source) {
  3183. var destination = creationFunction();
  3184. // Tags
  3185. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3186. // Properties
  3187. for (var property in destination.__serializableMembers) {
  3188. var propertyDescriptor = destination.__serializableMembers[property];
  3189. var sourceProperty = source[property];
  3190. var propertyType = propertyDescriptor.type;
  3191. if (sourceProperty !== undefined && sourceProperty !== null) {
  3192. switch (propertyType) {
  3193. case 0: // Value
  3194. case 6:
  3195. destination[property] = sourceProperty;
  3196. break;
  3197. case 1: // Texture
  3198. case 2: // Color3
  3199. case 3: // FresnelParameters
  3200. case 4: // Vector2
  3201. case 5:
  3202. destination[property] = sourceProperty.clone();
  3203. break;
  3204. }
  3205. }
  3206. }
  3207. return destination;
  3208. };
  3209. return SerializationHelper;
  3210. })();
  3211. BABYLON.SerializationHelper = SerializationHelper;
  3212. })(BABYLON || (BABYLON = {}));
  3213. var BABYLON;
  3214. (function (BABYLON) {
  3215. var Database = (function () {
  3216. function Database(urlToScene, callbackManifestChecked) {
  3217. // Handling various flavors of prefixed version of IndexedDB
  3218. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3219. this.callbackManifestChecked = callbackManifestChecked;
  3220. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3221. this.db = null;
  3222. this.enableSceneOffline = false;
  3223. this.enableTexturesOffline = false;
  3224. this.manifestVersionFound = 0;
  3225. this.mustUpdateRessources = false;
  3226. this.hasReachedQuota = false;
  3227. if (!Database.IDBStorageEnabled) {
  3228. this.callbackManifestChecked(true);
  3229. }
  3230. else {
  3231. this.checkManifestFile();
  3232. }
  3233. }
  3234. Database.prototype.checkManifestFile = function () {
  3235. var _this = this;
  3236. function noManifestFile() {
  3237. that.enableSceneOffline = false;
  3238. that.enableTexturesOffline = false;
  3239. that.callbackManifestChecked(false);
  3240. }
  3241. var that = this;
  3242. var timeStampUsed = false;
  3243. var manifestURL = this.currentSceneUrl + ".manifest";
  3244. var xhr = new XMLHttpRequest();
  3245. if (navigator.onLine) {
  3246. // Adding a timestamp to by-pass browsers' cache
  3247. timeStampUsed = true;
  3248. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3249. }
  3250. xhr.open("GET", manifestURL, true);
  3251. xhr.addEventListener("load", function () {
  3252. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3253. try {
  3254. var manifestFile = JSON.parse(xhr.response);
  3255. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3256. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3257. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3258. _this.manifestVersionFound = manifestFile.version;
  3259. }
  3260. if (_this.callbackManifestChecked) {
  3261. _this.callbackManifestChecked(true);
  3262. }
  3263. }
  3264. catch (ex) {
  3265. noManifestFile();
  3266. }
  3267. }
  3268. else {
  3269. noManifestFile();
  3270. }
  3271. }, false);
  3272. xhr.addEventListener("error", function (event) {
  3273. if (timeStampUsed) {
  3274. timeStampUsed = false;
  3275. // Let's retry without the timeStamp
  3276. // It could fail when coupled with HTML5 Offline API
  3277. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3278. xhr.open("GET", retryManifestURL, true);
  3279. xhr.send();
  3280. }
  3281. else {
  3282. noManifestFile();
  3283. }
  3284. }, false);
  3285. try {
  3286. xhr.send();
  3287. }
  3288. catch (ex) {
  3289. BABYLON.Tools.Error("Error on XHR send request.");
  3290. that.callbackManifestChecked(false);
  3291. }
  3292. };
  3293. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3294. var _this = this;
  3295. function handleError() {
  3296. that.isSupported = false;
  3297. if (errorCallback)
  3298. errorCallback();
  3299. }
  3300. var that = this;
  3301. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3302. // Your browser doesn't support IndexedDB
  3303. this.isSupported = false;
  3304. if (errorCallback)
  3305. errorCallback();
  3306. }
  3307. else {
  3308. // If the DB hasn't been opened or created yet
  3309. if (!this.db) {
  3310. this.hasReachedQuota = false;
  3311. this.isSupported = true;
  3312. var request = this.idbFactory.open("babylonjs", 1);
  3313. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3314. request.onerror = function (event) {
  3315. handleError();
  3316. };
  3317. // executes when a version change transaction cannot complete due to other active transactions
  3318. request.onblocked = function (event) {
  3319. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3320. handleError();
  3321. };
  3322. // DB has been opened successfully
  3323. request.onsuccess = function (event) {
  3324. _this.db = request.result;
  3325. successCallback();
  3326. };
  3327. // Initialization of the DB. Creating Scenes & Textures stores
  3328. request.onupgradeneeded = function (event) {
  3329. _this.db = (event.target).result;
  3330. try {
  3331. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3332. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3333. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3334. }
  3335. catch (ex) {
  3336. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3337. handleError();
  3338. }
  3339. };
  3340. }
  3341. else {
  3342. if (successCallback)
  3343. successCallback();
  3344. }
  3345. }
  3346. };
  3347. Database.prototype.loadImageFromDB = function (url, image) {
  3348. var _this = this;
  3349. var completeURL = Database.ReturnFullUrlLocation(url);
  3350. var saveAndLoadImage = function () {
  3351. if (!_this.hasReachedQuota && _this.db !== null) {
  3352. // the texture is not yet in the DB, let's try to save it
  3353. _this._saveImageIntoDBAsync(completeURL, image);
  3354. }
  3355. else {
  3356. image.src = url;
  3357. }
  3358. };
  3359. if (!this.mustUpdateRessources) {
  3360. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3361. }
  3362. else {
  3363. saveAndLoadImage();
  3364. }
  3365. };
  3366. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3367. if (this.isSupported && this.db !== null) {
  3368. var texture;
  3369. var transaction = this.db.transaction(["textures"]);
  3370. transaction.onabort = function (event) {
  3371. image.src = url;
  3372. };
  3373. transaction.oncomplete = function (event) {
  3374. var blobTextureURL;
  3375. if (texture) {
  3376. var URL = window.URL || window.webkitURL;
  3377. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3378. image.onerror = function () {
  3379. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3380. image.src = url;
  3381. };
  3382. image.src = blobTextureURL;
  3383. }
  3384. else {
  3385. notInDBCallback();
  3386. }
  3387. };
  3388. var getRequest = transaction.objectStore("textures").get(url);
  3389. getRequest.onsuccess = function (event) {
  3390. texture = (event.target).result;
  3391. };
  3392. getRequest.onerror = function (event) {
  3393. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3394. image.src = url;
  3395. };
  3396. }
  3397. else {
  3398. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3399. image.src = url;
  3400. }
  3401. };
  3402. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3403. var _this = this;
  3404. if (this.isSupported) {
  3405. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3406. var generateBlobUrl = function () {
  3407. var blobTextureURL;
  3408. if (blob) {
  3409. var URL = window.URL || window.webkitURL;
  3410. try {
  3411. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3412. }
  3413. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3414. catch (ex) {
  3415. blobTextureURL = URL.createObjectURL(blob);
  3416. }
  3417. }
  3418. image.src = blobTextureURL;
  3419. };
  3420. if (Database.IsUASupportingBlobStorage) {
  3421. var xhr = new XMLHttpRequest(), blob;
  3422. xhr.open("GET", url, true);
  3423. xhr.responseType = "blob";
  3424. xhr.addEventListener("load", function () {
  3425. if (xhr.status === 200) {
  3426. // Blob as response (XHR2)
  3427. blob = xhr.response;
  3428. var transaction = _this.db.transaction(["textures"], "readwrite");
  3429. // the transaction could abort because of a QuotaExceededError error
  3430. transaction.onabort = function (event) {
  3431. try {
  3432. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3433. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3434. this.hasReachedQuota = true;
  3435. }
  3436. }
  3437. catch (ex) { }
  3438. generateBlobUrl();
  3439. };
  3440. transaction.oncomplete = function (event) {
  3441. generateBlobUrl();
  3442. };
  3443. var newTexture = { textureUrl: url, data: blob };
  3444. try {
  3445. // Put the blob into the dabase
  3446. var addRequest = transaction.objectStore("textures").put(newTexture);
  3447. addRequest.onsuccess = function (event) {
  3448. };
  3449. addRequest.onerror = function (event) {
  3450. generateBlobUrl();
  3451. };
  3452. }
  3453. catch (ex) {
  3454. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3455. if (ex.code === 25) {
  3456. Database.IsUASupportingBlobStorage = false;
  3457. }
  3458. image.src = url;
  3459. }
  3460. }
  3461. else {
  3462. image.src = url;
  3463. }
  3464. }, false);
  3465. xhr.addEventListener("error", function (event) {
  3466. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3467. image.src = url;
  3468. }, false);
  3469. xhr.send();
  3470. }
  3471. else {
  3472. image.src = url;
  3473. }
  3474. }
  3475. else {
  3476. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3477. image.src = url;
  3478. }
  3479. };
  3480. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3481. var _this = this;
  3482. var updateVersion = function (event) {
  3483. // the version is not yet in the DB or we need to update it
  3484. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3485. };
  3486. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3487. };
  3488. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3489. var _this = this;
  3490. if (this.isSupported) {
  3491. var version;
  3492. try {
  3493. var transaction = this.db.transaction(["versions"]);
  3494. transaction.oncomplete = function (event) {
  3495. if (version) {
  3496. // If the version in the JSON file is > than the version in DB
  3497. if (_this.manifestVersionFound > version.data) {
  3498. _this.mustUpdateRessources = true;
  3499. updateInDBCallback();
  3500. }
  3501. else {
  3502. callback(version.data);
  3503. }
  3504. }
  3505. else {
  3506. _this.mustUpdateRessources = true;
  3507. updateInDBCallback();
  3508. }
  3509. };
  3510. transaction.onabort = function (event) {
  3511. callback(-1);
  3512. };
  3513. var getRequest = transaction.objectStore("versions").get(url);
  3514. getRequest.onsuccess = function (event) {
  3515. version = (event.target).result;
  3516. };
  3517. getRequest.onerror = function (event) {
  3518. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3519. callback(-1);
  3520. };
  3521. }
  3522. catch (ex) {
  3523. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3524. callback(-1);
  3525. }
  3526. }
  3527. else {
  3528. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3529. callback(-1);
  3530. }
  3531. };
  3532. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3533. var _this = this;
  3534. if (this.isSupported && !this.hasReachedQuota) {
  3535. try {
  3536. // Open a transaction to the database
  3537. var transaction = this.db.transaction(["versions"], "readwrite");
  3538. // the transaction could abort because of a QuotaExceededError error
  3539. transaction.onabort = function (event) {
  3540. try {
  3541. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3542. _this.hasReachedQuota = true;
  3543. }
  3544. }
  3545. catch (ex) { }
  3546. callback(-1);
  3547. };
  3548. transaction.oncomplete = function (event) {
  3549. callback(_this.manifestVersionFound);
  3550. };
  3551. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3552. // Put the scene into the database
  3553. var addRequest = transaction.objectStore("versions").put(newVersion);
  3554. addRequest.onsuccess = function (event) {
  3555. };
  3556. addRequest.onerror = function (event) {
  3557. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3558. };
  3559. }
  3560. catch (ex) {
  3561. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3562. callback(-1);
  3563. }
  3564. }
  3565. else {
  3566. callback(-1);
  3567. }
  3568. };
  3569. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3570. var _this = this;
  3571. var completeUrl = Database.ReturnFullUrlLocation(url);
  3572. var saveAndLoadFile = function (event) {
  3573. // the scene is not yet in the DB, let's try to save it
  3574. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3575. };
  3576. this._checkVersionFromDB(completeUrl, function (version) {
  3577. if (version !== -1) {
  3578. if (!_this.mustUpdateRessources) {
  3579. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3580. }
  3581. else {
  3582. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3583. }
  3584. }
  3585. else {
  3586. errorCallback();
  3587. }
  3588. });
  3589. };
  3590. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3591. if (this.isSupported) {
  3592. var targetStore;
  3593. if (url.indexOf(".babylon") !== -1) {
  3594. targetStore = "scenes";
  3595. }
  3596. else {
  3597. targetStore = "textures";
  3598. }
  3599. var file;
  3600. var transaction = this.db.transaction([targetStore]);
  3601. transaction.oncomplete = function (event) {
  3602. if (file) {
  3603. callback(file.data);
  3604. }
  3605. else {
  3606. notInDBCallback();
  3607. }
  3608. };
  3609. transaction.onabort = function (event) {
  3610. notInDBCallback();
  3611. };
  3612. var getRequest = transaction.objectStore(targetStore).get(url);
  3613. getRequest.onsuccess = function (event) {
  3614. file = (event.target).result;
  3615. };
  3616. getRequest.onerror = function (event) {
  3617. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3618. notInDBCallback();
  3619. };
  3620. }
  3621. else {
  3622. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3623. callback();
  3624. }
  3625. };
  3626. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3627. var _this = this;
  3628. if (this.isSupported) {
  3629. var targetStore;
  3630. if (url.indexOf(".babylon") !== -1) {
  3631. targetStore = "scenes";
  3632. }
  3633. else {
  3634. targetStore = "textures";
  3635. }
  3636. // Create XHR
  3637. var xhr = new XMLHttpRequest(), fileData;
  3638. xhr.open("GET", url, true);
  3639. if (useArrayBuffer) {
  3640. xhr.responseType = "arraybuffer";
  3641. }
  3642. xhr.onprogress = progressCallback;
  3643. xhr.addEventListener("load", function () {
  3644. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3645. // Blob as response (XHR2)
  3646. //fileData = xhr.responseText;
  3647. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3648. if (!_this.hasReachedQuota) {
  3649. // Open a transaction to the database
  3650. var transaction = _this.db.transaction([targetStore], "readwrite");
  3651. // the transaction could abort because of a QuotaExceededError error
  3652. transaction.onabort = function (event) {
  3653. try {
  3654. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3655. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3656. this.hasReachedQuota = true;
  3657. }
  3658. }
  3659. catch (ex) { }
  3660. callback(fileData);
  3661. };
  3662. transaction.oncomplete = function (event) {
  3663. callback(fileData);
  3664. };
  3665. var newFile;
  3666. if (targetStore === "scenes") {
  3667. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3668. }
  3669. else {
  3670. newFile = { textureUrl: url, data: fileData };
  3671. }
  3672. try {
  3673. // Put the scene into the database
  3674. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3675. addRequest.onsuccess = function (event) {
  3676. };
  3677. addRequest.onerror = function (event) {
  3678. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3679. };
  3680. }
  3681. catch (ex) {
  3682. callback(fileData);
  3683. }
  3684. }
  3685. else {
  3686. callback(fileData);
  3687. }
  3688. }
  3689. else {
  3690. callback();
  3691. }
  3692. }, false);
  3693. xhr.addEventListener("error", function (event) {
  3694. BABYLON.Tools.Error("error on XHR request.");
  3695. callback();
  3696. }, false);
  3697. xhr.send();
  3698. }
  3699. else {
  3700. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3701. callback();
  3702. }
  3703. };
  3704. Database.IsUASupportingBlobStorage = true;
  3705. Database.IDBStorageEnabled = true;
  3706. Database.parseURL = function (url) {
  3707. var a = document.createElement('a');
  3708. a.href = url;
  3709. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3710. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3711. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3712. return absLocation;
  3713. };
  3714. Database.ReturnFullUrlLocation = function (url) {
  3715. if (url.indexOf("http:/") === -1) {
  3716. return (Database.parseURL(window.location.href) + url);
  3717. }
  3718. else {
  3719. return url;
  3720. }
  3721. };
  3722. return Database;
  3723. })();
  3724. BABYLON.Database = Database;
  3725. })(BABYLON || (BABYLON = {}));
  3726. var BABYLON;
  3727. (function (BABYLON) {
  3728. var Internals;
  3729. (function (Internals) {
  3730. /*
  3731. * Based on jsTGALoader - Javascript loader for TGA file
  3732. * By Vincent Thibault
  3733. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3734. */
  3735. var TGATools = (function () {
  3736. function TGATools() {
  3737. }
  3738. TGATools.GetTGAHeader = function (data) {
  3739. var offset = 0;
  3740. var header = {
  3741. id_length: data[offset++],
  3742. colormap_type: data[offset++],
  3743. image_type: data[offset++],
  3744. colormap_index: data[offset++] | data[offset++] << 8,
  3745. colormap_length: data[offset++] | data[offset++] << 8,
  3746. colormap_size: data[offset++],
  3747. origin: [
  3748. data[offset++] | data[offset++] << 8,
  3749. data[offset++] | data[offset++] << 8
  3750. ],
  3751. width: data[offset++] | data[offset++] << 8,
  3752. height: data[offset++] | data[offset++] << 8,
  3753. pixel_size: data[offset++],
  3754. flags: data[offset++]
  3755. };
  3756. return header;
  3757. };
  3758. TGATools.UploadContent = function (gl, data) {
  3759. // Not enough data to contain header ?
  3760. if (data.length < 19) {
  3761. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3762. return;
  3763. }
  3764. // Read Header
  3765. var offset = 18;
  3766. var header = TGATools.GetTGAHeader(data);
  3767. // Assume it's a valid Targa file.
  3768. if (header.id_length + offset > data.length) {
  3769. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3770. return;
  3771. }
  3772. // Skip not needed data
  3773. offset += header.id_length;
  3774. var use_rle = false;
  3775. var use_pal = false;
  3776. var use_rgb = false;
  3777. var use_grey = false;
  3778. // Get some informations.
  3779. switch (header.image_type) {
  3780. case TGATools._TYPE_RLE_INDEXED:
  3781. use_rle = true;
  3782. case TGATools._TYPE_INDEXED:
  3783. use_pal = true;
  3784. break;
  3785. case TGATools._TYPE_RLE_RGB:
  3786. use_rle = true;
  3787. case TGATools._TYPE_RGB:
  3788. use_rgb = true;
  3789. break;
  3790. case TGATools._TYPE_RLE_GREY:
  3791. use_rle = true;
  3792. case TGATools._TYPE_GREY:
  3793. use_grey = true;
  3794. break;
  3795. }
  3796. var pixel_data;
  3797. var numAlphaBits = header.flags & 0xf;
  3798. var pixel_size = header.pixel_size >> 3;
  3799. var pixel_total = header.width * header.height * pixel_size;
  3800. // Read palettes
  3801. var palettes;
  3802. if (use_pal) {
  3803. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3804. }
  3805. // Read LRE
  3806. if (use_rle) {
  3807. pixel_data = new Uint8Array(pixel_total);
  3808. var c, count, i;
  3809. var localOffset = 0;
  3810. var pixels = new Uint8Array(pixel_size);
  3811. while (offset < pixel_total && localOffset < pixel_total) {
  3812. c = data[offset++];
  3813. count = (c & 0x7f) + 1;
  3814. // RLE pixels
  3815. if (c & 0x80) {
  3816. // Bind pixel tmp array
  3817. for (i = 0; i < pixel_size; ++i) {
  3818. pixels[i] = data[offset++];
  3819. }
  3820. // Copy pixel array
  3821. for (i = 0; i < count; ++i) {
  3822. pixel_data.set(pixels, localOffset + i * pixel_size);
  3823. }
  3824. localOffset += pixel_size * count;
  3825. }
  3826. else {
  3827. count *= pixel_size;
  3828. for (i = 0; i < count; ++i) {
  3829. pixel_data[localOffset + i] = data[offset++];
  3830. }
  3831. localOffset += count;
  3832. }
  3833. }
  3834. }
  3835. else {
  3836. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3837. }
  3838. // Load to texture
  3839. var x_start, y_start, x_step, y_step, y_end, x_end;
  3840. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3841. default:
  3842. case TGATools._ORIGIN_UL:
  3843. x_start = 0;
  3844. x_step = 1;
  3845. x_end = header.width;
  3846. y_start = 0;
  3847. y_step = 1;
  3848. y_end = header.height;
  3849. break;
  3850. case TGATools._ORIGIN_BL:
  3851. x_start = 0;
  3852. x_step = 1;
  3853. x_end = header.width;
  3854. y_start = header.height - 1;
  3855. y_step = -1;
  3856. y_end = -1;
  3857. break;
  3858. case TGATools._ORIGIN_UR:
  3859. x_start = header.width - 1;
  3860. x_step = -1;
  3861. x_end = -1;
  3862. y_start = 0;
  3863. y_step = 1;
  3864. y_end = header.height;
  3865. break;
  3866. case TGATools._ORIGIN_BR:
  3867. x_start = header.width - 1;
  3868. x_step = -1;
  3869. x_end = -1;
  3870. y_start = header.height - 1;
  3871. y_step = -1;
  3872. y_end = -1;
  3873. break;
  3874. }
  3875. // Load the specify method
  3876. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3877. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3878. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3879. };
  3880. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3881. var image = pixel_data, colormap = palettes;
  3882. var width = header.width, height = header.height;
  3883. var color, i = 0, x, y;
  3884. var imageData = new Uint8Array(width * height * 4);
  3885. for (y = y_start; y !== y_end; y += y_step) {
  3886. for (x = x_start; x !== x_end; x += x_step, i++) {
  3887. color = image[i];
  3888. imageData[(x + width * y) * 4 + 3] = 255;
  3889. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3890. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3891. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3892. }
  3893. }
  3894. return imageData;
  3895. };
  3896. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3897. var image = pixel_data;
  3898. var width = header.width, height = header.height;
  3899. var color, i = 0, x, y;
  3900. var imageData = new Uint8Array(width * height * 4);
  3901. for (y = y_start; y !== y_end; y += y_step) {
  3902. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3903. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3904. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3905. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3906. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3907. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3908. }
  3909. }
  3910. return imageData;
  3911. };
  3912. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3913. var image = pixel_data;
  3914. var width = header.width, height = header.height;
  3915. var i = 0, x, y;
  3916. var imageData = new Uint8Array(width * height * 4);
  3917. for (y = y_start; y !== y_end; y += y_step) {
  3918. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3919. imageData[(x + width * y) * 4 + 3] = 255;
  3920. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3921. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3922. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3923. }
  3924. }
  3925. return imageData;
  3926. };
  3927. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3928. var image = pixel_data;
  3929. var width = header.width, height = header.height;
  3930. var i = 0, x, y;
  3931. var imageData = new Uint8Array(width * height * 4);
  3932. for (y = y_start; y !== y_end; y += y_step) {
  3933. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3934. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3935. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3936. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3937. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3938. }
  3939. }
  3940. return imageData;
  3941. };
  3942. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3943. var image = pixel_data;
  3944. var width = header.width, height = header.height;
  3945. var color, i = 0, x, y;
  3946. var imageData = new Uint8Array(width * height * 4);
  3947. for (y = y_start; y !== y_end; y += y_step) {
  3948. for (x = x_start; x !== x_end; x += x_step, i++) {
  3949. color = image[i];
  3950. imageData[(x + width * y) * 4 + 0] = color;
  3951. imageData[(x + width * y) * 4 + 1] = color;
  3952. imageData[(x + width * y) * 4 + 2] = color;
  3953. imageData[(x + width * y) * 4 + 3] = 255;
  3954. }
  3955. }
  3956. return imageData;
  3957. };
  3958. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3959. var image = pixel_data;
  3960. var width = header.width, height = header.height;
  3961. var i = 0, x, y;
  3962. var imageData = new Uint8Array(width * height * 4);
  3963. for (y = y_start; y !== y_end; y += y_step) {
  3964. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3965. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3966. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3967. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3968. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3969. }
  3970. }
  3971. return imageData;
  3972. };
  3973. TGATools._TYPE_NO_DATA = 0;
  3974. TGATools._TYPE_INDEXED = 1;
  3975. TGATools._TYPE_RGB = 2;
  3976. TGATools._TYPE_GREY = 3;
  3977. TGATools._TYPE_RLE_INDEXED = 9;
  3978. TGATools._TYPE_RLE_RGB = 10;
  3979. TGATools._TYPE_RLE_GREY = 11;
  3980. TGATools._ORIGIN_MASK = 0x30;
  3981. TGATools._ORIGIN_SHIFT = 0x04;
  3982. TGATools._ORIGIN_BL = 0x00;
  3983. TGATools._ORIGIN_BR = 0x01;
  3984. TGATools._ORIGIN_UL = 0x02;
  3985. TGATools._ORIGIN_UR = 0x03;
  3986. return TGATools;
  3987. })();
  3988. Internals.TGATools = TGATools;
  3989. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3990. })(BABYLON || (BABYLON = {}));
  3991. var BABYLON;
  3992. (function (BABYLON) {
  3993. var SmartArray = (function () {
  3994. function SmartArray(capacity) {
  3995. this.length = 0;
  3996. this._duplicateId = 0;
  3997. this.data = new Array(capacity);
  3998. this._id = SmartArray._GlobalId++;
  3999. }
  4000. SmartArray.prototype.push = function (value) {
  4001. this.data[this.length++] = value;
  4002. if (this.length > this.data.length) {
  4003. this.data.length *= 2;
  4004. }
  4005. if (!value.__smartArrayFlags) {
  4006. value.__smartArrayFlags = {};
  4007. }
  4008. value.__smartArrayFlags[this._id] = this._duplicateId;
  4009. };
  4010. SmartArray.prototype.pushNoDuplicate = function (value) {
  4011. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4012. return;
  4013. }
  4014. this.push(value);
  4015. };
  4016. SmartArray.prototype.sort = function (compareFn) {
  4017. this.data.sort(compareFn);
  4018. };
  4019. SmartArray.prototype.reset = function () {
  4020. this.length = 0;
  4021. this._duplicateId++;
  4022. };
  4023. SmartArray.prototype.concat = function (array) {
  4024. if (array.length === 0) {
  4025. return;
  4026. }
  4027. if (this.length + array.length > this.data.length) {
  4028. this.data.length = (this.length + array.length) * 2;
  4029. }
  4030. for (var index = 0; index < array.length; index++) {
  4031. this.data[this.length++] = (array.data || array)[index];
  4032. }
  4033. };
  4034. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4035. if (array.length === 0) {
  4036. return;
  4037. }
  4038. if (this.length + array.length > this.data.length) {
  4039. this.data.length = (this.length + array.length) * 2;
  4040. }
  4041. for (var index = 0; index < array.length; index++) {
  4042. var item = (array.data || array)[index];
  4043. this.pushNoDuplicate(item);
  4044. }
  4045. };
  4046. SmartArray.prototype.indexOf = function (value) {
  4047. var position = this.data.indexOf(value);
  4048. if (position >= this.length) {
  4049. return -1;
  4050. }
  4051. return position;
  4052. };
  4053. // Statics
  4054. SmartArray._GlobalId = 0;
  4055. return SmartArray;
  4056. })();
  4057. BABYLON.SmartArray = SmartArray;
  4058. })(BABYLON || (BABYLON = {}));
  4059. var BABYLON;
  4060. (function (BABYLON) {
  4061. var SmartCollection = (function () {
  4062. function SmartCollection(capacity) {
  4063. if (capacity === void 0) { capacity = 10; }
  4064. this.count = 0;
  4065. this._initialCapacity = capacity;
  4066. this.items = {};
  4067. this._keys = new Array(this._initialCapacity);
  4068. }
  4069. SmartCollection.prototype.add = function (key, item) {
  4070. if (this.items[key] != undefined) {
  4071. return -1;
  4072. }
  4073. this.items[key] = item;
  4074. //literal keys are always strings, but we keep source type of key in _keys array
  4075. this._keys[this.count++] = key;
  4076. if (this.count > this._keys.length) {
  4077. this._keys.length *= 2;
  4078. }
  4079. return this.count;
  4080. };
  4081. SmartCollection.prototype.remove = function (key) {
  4082. if (this.items[key] == undefined) {
  4083. return -1;
  4084. }
  4085. return this.removeItemOfIndex(this.indexOf(key));
  4086. };
  4087. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4088. if (index < this.count && index > -1) {
  4089. delete this.items[this._keys[index]];
  4090. //here, shifting by hand is better optimised than .splice
  4091. while (index < this.count) {
  4092. this._keys[index] = this._keys[index + 1];
  4093. index++;
  4094. }
  4095. }
  4096. else {
  4097. return -1;
  4098. }
  4099. return --this.count;
  4100. };
  4101. SmartCollection.prototype.indexOf = function (key) {
  4102. for (var i = 0; i !== this.count; i++) {
  4103. if (this._keys[i] === key) {
  4104. return i;
  4105. }
  4106. }
  4107. return -1;
  4108. };
  4109. SmartCollection.prototype.item = function (key) {
  4110. return this.items[key];
  4111. };
  4112. SmartCollection.prototype.getAllKeys = function () {
  4113. if (this.count > 0) {
  4114. var keys = new Array(this.count);
  4115. for (var i = 0; i < this.count; i++) {
  4116. keys[i] = this._keys[i];
  4117. }
  4118. return keys;
  4119. }
  4120. else {
  4121. return undefined;
  4122. }
  4123. };
  4124. SmartCollection.prototype.getKeyByIndex = function (index) {
  4125. if (index < this.count && index > -1) {
  4126. return this._keys[index];
  4127. }
  4128. else {
  4129. return undefined;
  4130. }
  4131. };
  4132. SmartCollection.prototype.getItemByIndex = function (index) {
  4133. if (index < this.count && index > -1) {
  4134. return this.items[this._keys[index]];
  4135. }
  4136. else {
  4137. return undefined;
  4138. }
  4139. };
  4140. SmartCollection.prototype.empty = function () {
  4141. if (this.count > 0) {
  4142. this.count = 0;
  4143. this.items = {};
  4144. this._keys = new Array(this._initialCapacity);
  4145. }
  4146. };
  4147. SmartCollection.prototype.forEach = function (block) {
  4148. var key;
  4149. for (key in this.items) {
  4150. if (this.items.hasOwnProperty(key)) {
  4151. block(this.items[key]);
  4152. }
  4153. }
  4154. };
  4155. return SmartCollection;
  4156. })();
  4157. BABYLON.SmartCollection = SmartCollection;
  4158. })(BABYLON || (BABYLON = {}));
  4159. var BABYLON;
  4160. (function (BABYLON) {
  4161. // Screenshots
  4162. var screenshotCanvas;
  4163. var cloneValue = function (source, destinationObject) {
  4164. if (!source)
  4165. return null;
  4166. if (source instanceof BABYLON.Mesh) {
  4167. return null;
  4168. }
  4169. if (source instanceof BABYLON.SubMesh) {
  4170. return source.clone(destinationObject);
  4171. }
  4172. else if (source.clone) {
  4173. return source.clone();
  4174. }
  4175. return null;
  4176. };
  4177. var Tools = (function () {
  4178. function Tools() {
  4179. }
  4180. Tools.Instantiate = function (className) {
  4181. var arr = className.split(".");
  4182. var fn = (window || this);
  4183. for (var i = 0, len = arr.length; i < len; i++) {
  4184. fn = fn[arr[i]];
  4185. }
  4186. if (typeof fn !== "function") {
  4187. return null;
  4188. }
  4189. return fn;
  4190. };
  4191. Tools.ToHex = function (i) {
  4192. var str = i.toString(16);
  4193. if (i <= 15) {
  4194. return ("0" + str).toUpperCase();
  4195. }
  4196. return str.toUpperCase();
  4197. };
  4198. Tools.SetImmediate = function (action) {
  4199. if (window.setImmediate) {
  4200. window.setImmediate(action);
  4201. }
  4202. else {
  4203. setTimeout(action, 1);
  4204. }
  4205. };
  4206. Tools.IsExponentOfTwo = function (value) {
  4207. var count = 1;
  4208. do {
  4209. count *= 2;
  4210. } while (count < value);
  4211. return count === value;
  4212. };
  4213. Tools.GetExponentOfTwo = function (value, max) {
  4214. var count = 1;
  4215. do {
  4216. count *= 2;
  4217. } while (count < value);
  4218. if (count > max)
  4219. count = max;
  4220. return count;
  4221. };
  4222. Tools.GetFilename = function (path) {
  4223. var index = path.lastIndexOf("/");
  4224. if (index < 0)
  4225. return path;
  4226. return path.substring(index + 1);
  4227. };
  4228. Tools.GetDOMTextContent = function (element) {
  4229. var result = "";
  4230. var child = element.firstChild;
  4231. while (child) {
  4232. if (child.nodeType === 3) {
  4233. result += child.textContent;
  4234. }
  4235. child = child.nextSibling;
  4236. }
  4237. return result;
  4238. };
  4239. Tools.ToDegrees = function (angle) {
  4240. return angle * 180 / Math.PI;
  4241. };
  4242. Tools.ToRadians = function (angle) {
  4243. return angle * Math.PI / 180;
  4244. };
  4245. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4246. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4247. var output = "";
  4248. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4249. var i = 0;
  4250. var bytes = new Uint8Array(buffer);
  4251. while (i < bytes.length) {
  4252. chr1 = bytes[i++];
  4253. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4254. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4255. enc1 = chr1 >> 2;
  4256. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4257. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4258. enc4 = chr3 & 63;
  4259. if (isNaN(chr2)) {
  4260. enc3 = enc4 = 64;
  4261. }
  4262. else if (isNaN(chr3)) {
  4263. enc4 = 64;
  4264. }
  4265. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4266. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4267. }
  4268. return "data:image/png;base64," + output;
  4269. };
  4270. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4271. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4272. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4273. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4274. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4275. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4276. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4277. }
  4278. return {
  4279. minimum: minimum,
  4280. maximum: maximum
  4281. };
  4282. };
  4283. Tools.ExtractMinAndMax = function (positions, start, count) {
  4284. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4285. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4286. for (var index = start; index < start + count; index++) {
  4287. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4288. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4289. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4290. }
  4291. return {
  4292. minimum: minimum,
  4293. maximum: maximum
  4294. };
  4295. };
  4296. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4297. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4298. return undefined;
  4299. return Array.isArray(obj) ? obj : [obj];
  4300. };
  4301. // Misc.
  4302. Tools.GetPointerPrefix = function () {
  4303. var eventPrefix = "pointer";
  4304. // Check if pointer events are supported
  4305. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4306. eventPrefix = "mouse";
  4307. }
  4308. return eventPrefix;
  4309. };
  4310. Tools.QueueNewFrame = function (func) {
  4311. if (window.requestAnimationFrame)
  4312. window.requestAnimationFrame(func);
  4313. else if (window.msRequestAnimationFrame)
  4314. window.msRequestAnimationFrame(func);
  4315. else if (window.webkitRequestAnimationFrame)
  4316. window.webkitRequestAnimationFrame(func);
  4317. else if (window.mozRequestAnimationFrame)
  4318. window.mozRequestAnimationFrame(func);
  4319. else if (window.oRequestAnimationFrame)
  4320. window.oRequestAnimationFrame(func);
  4321. else {
  4322. window.setTimeout(func, 16);
  4323. }
  4324. };
  4325. Tools.RequestFullscreen = function (element) {
  4326. if (element.requestFullscreen)
  4327. element.requestFullscreen();
  4328. else if (element.msRequestFullscreen)
  4329. element.msRequestFullscreen();
  4330. else if (element.webkitRequestFullscreen)
  4331. element.webkitRequestFullscreen();
  4332. else if (element.mozRequestFullScreen)
  4333. element.mozRequestFullScreen();
  4334. };
  4335. Tools.ExitFullscreen = function () {
  4336. if (document.exitFullscreen) {
  4337. document.exitFullscreen();
  4338. }
  4339. else if (document.mozCancelFullScreen) {
  4340. document.mozCancelFullScreen();
  4341. }
  4342. else if (document.webkitCancelFullScreen) {
  4343. document.webkitCancelFullScreen();
  4344. }
  4345. else if (document.msCancelFullScreen) {
  4346. document.msCancelFullScreen();
  4347. }
  4348. };
  4349. // External files
  4350. Tools.CleanUrl = function (url) {
  4351. url = url.replace(/#/mg, "%23");
  4352. return url;
  4353. };
  4354. Tools.LoadImage = function (url, onload, onerror, database) {
  4355. if (url instanceof ArrayBuffer) {
  4356. url = Tools.EncodeArrayBufferTobase64(url);
  4357. }
  4358. url = Tools.CleanUrl(url);
  4359. var img = new Image();
  4360. if (url.substr(0, 5) !== "data:") {
  4361. if (Tools.CorsBehavior) {
  4362. switch (typeof (Tools.CorsBehavior)) {
  4363. case "function":
  4364. var result = Tools.CorsBehavior(url);
  4365. if (result) {
  4366. img.crossOrigin = result;
  4367. }
  4368. break;
  4369. case "string":
  4370. default:
  4371. img.crossOrigin = Tools.CorsBehavior;
  4372. break;
  4373. }
  4374. }
  4375. }
  4376. img.onload = function () {
  4377. onload(img);
  4378. };
  4379. img.onerror = function (err) {
  4380. Tools.Error("Error while trying to load texture: " + url);
  4381. if (Tools.UseFallbackTexture) {
  4382. 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";
  4383. onload(img);
  4384. }
  4385. else {
  4386. onerror();
  4387. }
  4388. };
  4389. var noIndexedDB = function () {
  4390. img.src = url;
  4391. };
  4392. var loadFromIndexedDB = function () {
  4393. database.loadImageFromDB(url, img);
  4394. };
  4395. //ANY database to do!
  4396. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4397. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4398. }
  4399. else {
  4400. if (url.indexOf("file:") === -1) {
  4401. noIndexedDB();
  4402. }
  4403. else {
  4404. try {
  4405. var textureName = url.substring(5);
  4406. var blobURL;
  4407. try {
  4408. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4409. }
  4410. catch (ex) {
  4411. // Chrome doesn't support oneTimeOnly parameter
  4412. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4413. }
  4414. img.src = blobURL;
  4415. }
  4416. catch (e) {
  4417. img.src = null;
  4418. }
  4419. }
  4420. }
  4421. return img;
  4422. };
  4423. //ANY
  4424. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4425. url = Tools.CleanUrl(url);
  4426. var noIndexedDB = function () {
  4427. var request = new XMLHttpRequest();
  4428. var loadUrl = Tools.BaseUrl + url;
  4429. request.open('GET', loadUrl, true);
  4430. if (useArrayBuffer) {
  4431. request.responseType = "arraybuffer";
  4432. }
  4433. request.onprogress = progressCallBack;
  4434. request.onreadystatechange = function () {
  4435. if (request.readyState === 4) {
  4436. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4437. callback(!useArrayBuffer ? request.responseText : request.response);
  4438. }
  4439. else {
  4440. if (onError) {
  4441. onError();
  4442. }
  4443. else {
  4444. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4445. }
  4446. }
  4447. }
  4448. };
  4449. request.send(null);
  4450. };
  4451. var loadFromIndexedDB = function () {
  4452. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4453. };
  4454. if (url.indexOf("file:") !== -1) {
  4455. var fileName = url.substring(5);
  4456. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4457. }
  4458. else {
  4459. // Caching all files
  4460. if (database && database.enableSceneOffline) {
  4461. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4462. }
  4463. else {
  4464. noIndexedDB();
  4465. }
  4466. }
  4467. };
  4468. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4469. var reader = new FileReader();
  4470. reader.onload = function (e) {
  4471. //target doesn't have result from ts 1.3
  4472. callback(e.target['result']);
  4473. };
  4474. reader.onprogress = progressCallback;
  4475. reader.readAsDataURL(fileToLoad);
  4476. };
  4477. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4478. var reader = new FileReader();
  4479. reader.onerror = function (e) {
  4480. Tools.Log("Error while reading file: " + fileToLoad.name);
  4481. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4482. };
  4483. reader.onload = function (e) {
  4484. //target doesn't have result from ts 1.3
  4485. callback(e.target['result']);
  4486. };
  4487. reader.onprogress = progressCallBack;
  4488. if (!useArrayBuffer) {
  4489. // Asynchronous read
  4490. reader.readAsText(fileToLoad);
  4491. }
  4492. else {
  4493. reader.readAsArrayBuffer(fileToLoad);
  4494. }
  4495. };
  4496. //returns a downloadable url to a file content.
  4497. Tools.FileAsURL = function (content) {
  4498. var fileBlob = new Blob([content]);
  4499. var url = window.URL || window.webkitURL;
  4500. var link = url.createObjectURL(fileBlob);
  4501. return link;
  4502. };
  4503. // Misc.
  4504. Tools.Clamp = function (value, min, max) {
  4505. if (min === void 0) { min = 0; }
  4506. if (max === void 0) { max = 1; }
  4507. return Math.min(max, Math.max(min, value));
  4508. };
  4509. // Returns -1 when value is a negative number and
  4510. // +1 when value is a positive number.
  4511. Tools.Sign = function (value) {
  4512. value = +value; // convert to a number
  4513. if (value === 0 || isNaN(value))
  4514. return value;
  4515. return value > 0 ? 1 : -1;
  4516. };
  4517. Tools.Format = function (value, decimals) {
  4518. if (decimals === void 0) { decimals = 2; }
  4519. return value.toFixed(decimals);
  4520. };
  4521. Tools.CheckExtends = function (v, min, max) {
  4522. if (v.x < min.x)
  4523. min.x = v.x;
  4524. if (v.y < min.y)
  4525. min.y = v.y;
  4526. if (v.z < min.z)
  4527. min.z = v.z;
  4528. if (v.x > max.x)
  4529. max.x = v.x;
  4530. if (v.y > max.y)
  4531. max.y = v.y;
  4532. if (v.z > max.z)
  4533. max.z = v.z;
  4534. };
  4535. Tools.WithinEpsilon = function (a, b, epsilon) {
  4536. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4537. var num = a - b;
  4538. return -epsilon <= num && num <= epsilon;
  4539. };
  4540. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4541. for (var prop in source) {
  4542. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4543. continue;
  4544. }
  4545. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4546. continue;
  4547. }
  4548. var sourceValue = source[prop];
  4549. var typeOfSourceValue = typeof sourceValue;
  4550. if (typeOfSourceValue === "function") {
  4551. continue;
  4552. }
  4553. if (typeOfSourceValue === "object") {
  4554. if (sourceValue instanceof Array) {
  4555. destination[prop] = [];
  4556. if (sourceValue.length > 0) {
  4557. if (typeof sourceValue[0] == "object") {
  4558. for (var index = 0; index < sourceValue.length; index++) {
  4559. var clonedValue = cloneValue(sourceValue[index], destination);
  4560. if (destination[prop].indexOf(clonedValue) === -1) {
  4561. destination[prop].push(clonedValue);
  4562. }
  4563. }
  4564. }
  4565. else {
  4566. destination[prop] = sourceValue.slice(0);
  4567. }
  4568. }
  4569. }
  4570. else {
  4571. destination[prop] = cloneValue(sourceValue, destination);
  4572. }
  4573. }
  4574. else {
  4575. destination[prop] = sourceValue;
  4576. }
  4577. }
  4578. };
  4579. Tools.IsEmpty = function (obj) {
  4580. for (var i in obj) {
  4581. return false;
  4582. }
  4583. return true;
  4584. };
  4585. Tools.RegisterTopRootEvents = function (events) {
  4586. for (var index = 0; index < events.length; index++) {
  4587. var event = events[index];
  4588. window.addEventListener(event.name, event.handler, false);
  4589. try {
  4590. if (window.parent) {
  4591. window.parent.addEventListener(event.name, event.handler, false);
  4592. }
  4593. }
  4594. catch (e) {
  4595. }
  4596. }
  4597. };
  4598. Tools.UnregisterTopRootEvents = function (events) {
  4599. for (var index = 0; index < events.length; index++) {
  4600. var event = events[index];
  4601. window.removeEventListener(event.name, event.handler);
  4602. try {
  4603. if (window.parent) {
  4604. window.parent.removeEventListener(event.name, event.handler);
  4605. }
  4606. }
  4607. catch (e) {
  4608. }
  4609. }
  4610. };
  4611. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4612. // Read the contents of the framebuffer
  4613. var numberOfChannelsByLine = width * 4;
  4614. var halfHeight = height / 2;
  4615. //Reading datas from WebGL
  4616. var data = engine.readPixels(0, 0, width, height);
  4617. //To flip image on Y axis.
  4618. for (var i = 0; i < halfHeight; i++) {
  4619. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4620. var currentCell = j + i * numberOfChannelsByLine;
  4621. var targetLine = height - i - 1;
  4622. var targetCell = j + targetLine * numberOfChannelsByLine;
  4623. var temp = data[currentCell];
  4624. data[currentCell] = data[targetCell];
  4625. data[targetCell] = temp;
  4626. }
  4627. }
  4628. // Create a 2D canvas to store the result
  4629. if (!screenshotCanvas) {
  4630. screenshotCanvas = document.createElement('canvas');
  4631. }
  4632. screenshotCanvas.width = width;
  4633. screenshotCanvas.height = height;
  4634. var context = screenshotCanvas.getContext('2d');
  4635. // Copy the pixels to a 2D canvas
  4636. var imageData = context.createImageData(width, height);
  4637. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4638. var castData = imageData.data;
  4639. castData.set(data);
  4640. context.putImageData(imageData, 0, 0);
  4641. var base64Image = screenshotCanvas.toDataURL();
  4642. if (successCallback) {
  4643. successCallback(base64Image);
  4644. }
  4645. else {
  4646. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4647. if (("download" in document.createElement("a"))) {
  4648. var a = window.document.createElement("a");
  4649. a.href = base64Image;
  4650. var date = new Date();
  4651. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4652. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4653. window.document.body.appendChild(a);
  4654. a.addEventListener("click", function () {
  4655. a.parentElement.removeChild(a);
  4656. });
  4657. a.click();
  4658. }
  4659. else {
  4660. var newWindow = window.open("");
  4661. var img = newWindow.document.createElement("img");
  4662. img.src = base64Image;
  4663. newWindow.document.body.appendChild(img);
  4664. }
  4665. }
  4666. };
  4667. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4668. var width;
  4669. var height;
  4670. //If a precision value is specified
  4671. if (size.precision) {
  4672. width = Math.round(engine.getRenderWidth() * size.precision);
  4673. height = Math.round(width / engine.getAspectRatio(camera));
  4674. size = { width: width, height: height };
  4675. }
  4676. else if (size.width && size.height) {
  4677. width = size.width;
  4678. height = size.height;
  4679. }
  4680. else if (size.width && !size.height) {
  4681. width = size.width;
  4682. height = Math.round(width / engine.getAspectRatio(camera));
  4683. size = { width: width, height: height };
  4684. }
  4685. else if (size.height && !size.width) {
  4686. height = size.height;
  4687. width = Math.round(height * engine.getAspectRatio(camera));
  4688. size = { width: width, height: height };
  4689. }
  4690. else if (!isNaN(size)) {
  4691. height = size;
  4692. width = size;
  4693. }
  4694. else {
  4695. Tools.Error("Invalid 'size' parameter !");
  4696. return;
  4697. }
  4698. var scene = camera.getScene();
  4699. var previousCamera = null;
  4700. if (scene.activeCamera !== camera) {
  4701. previousCamera = scene.activeCamera;
  4702. scene.activeCamera = camera;
  4703. }
  4704. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4705. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4706. texture.renderList = scene.meshes;
  4707. texture.onAfterRender = function () {
  4708. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4709. };
  4710. scene.incrementRenderId();
  4711. texture.render(true);
  4712. texture.dispose();
  4713. if (previousCamera) {
  4714. scene.activeCamera = previousCamera;
  4715. }
  4716. camera.getProjectionMatrix(true); // Force cache refresh;
  4717. };
  4718. // XHR response validator for local file scenario
  4719. Tools.ValidateXHRData = function (xhr, dataType) {
  4720. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4721. if (dataType === void 0) { dataType = 7; }
  4722. try {
  4723. if (dataType & 1) {
  4724. if (xhr.responseText && xhr.responseText.length > 0) {
  4725. return true;
  4726. }
  4727. else if (dataType === 1) {
  4728. return false;
  4729. }
  4730. }
  4731. if (dataType & 2) {
  4732. // Check header width and height since there is no "TGA" magic number
  4733. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4734. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4735. return true;
  4736. }
  4737. else if (dataType === 2) {
  4738. return false;
  4739. }
  4740. }
  4741. if (dataType & 4) {
  4742. // Check for the "DDS" magic number
  4743. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4744. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4745. return true;
  4746. }
  4747. else {
  4748. return false;
  4749. }
  4750. }
  4751. }
  4752. catch (e) {
  4753. }
  4754. return false;
  4755. };
  4756. Object.defineProperty(Tools, "NoneLogLevel", {
  4757. get: function () {
  4758. return Tools._NoneLogLevel;
  4759. },
  4760. enumerable: true,
  4761. configurable: true
  4762. });
  4763. Object.defineProperty(Tools, "MessageLogLevel", {
  4764. get: function () {
  4765. return Tools._MessageLogLevel;
  4766. },
  4767. enumerable: true,
  4768. configurable: true
  4769. });
  4770. Object.defineProperty(Tools, "WarningLogLevel", {
  4771. get: function () {
  4772. return Tools._WarningLogLevel;
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. Object.defineProperty(Tools, "ErrorLogLevel", {
  4778. get: function () {
  4779. return Tools._ErrorLogLevel;
  4780. },
  4781. enumerable: true,
  4782. configurable: true
  4783. });
  4784. Object.defineProperty(Tools, "AllLogLevel", {
  4785. get: function () {
  4786. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4787. },
  4788. enumerable: true,
  4789. configurable: true
  4790. });
  4791. Tools._AddLogEntry = function (entry) {
  4792. Tools._LogCache = entry + Tools._LogCache;
  4793. if (Tools.OnNewCacheEntry) {
  4794. Tools.OnNewCacheEntry(entry);
  4795. }
  4796. };
  4797. Tools._FormatMessage = function (message) {
  4798. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4799. var date = new Date();
  4800. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4801. };
  4802. Tools._LogDisabled = function (message) {
  4803. // nothing to do
  4804. };
  4805. Tools._LogEnabled = function (message) {
  4806. var formattedMessage = Tools._FormatMessage(message);
  4807. console.log("BJS - " + formattedMessage);
  4808. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4809. Tools._AddLogEntry(entry);
  4810. };
  4811. Tools._WarnDisabled = function (message) {
  4812. // nothing to do
  4813. };
  4814. Tools._WarnEnabled = function (message) {
  4815. var formattedMessage = Tools._FormatMessage(message);
  4816. console.warn("BJS - " + formattedMessage);
  4817. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4818. Tools._AddLogEntry(entry);
  4819. };
  4820. Tools._ErrorDisabled = function (message) {
  4821. // nothing to do
  4822. };
  4823. Tools._ErrorEnabled = function (message) {
  4824. Tools.errorsCount++;
  4825. var formattedMessage = Tools._FormatMessage(message);
  4826. console.error("BJS - " + formattedMessage);
  4827. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4828. Tools._AddLogEntry(entry);
  4829. };
  4830. Object.defineProperty(Tools, "LogCache", {
  4831. get: function () {
  4832. return Tools._LogCache;
  4833. },
  4834. enumerable: true,
  4835. configurable: true
  4836. });
  4837. Tools.ClearLogCache = function () {
  4838. Tools._LogCache = "";
  4839. Tools.errorsCount = 0;
  4840. };
  4841. Object.defineProperty(Tools, "LogLevels", {
  4842. set: function (level) {
  4843. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4844. Tools.Log = Tools._LogEnabled;
  4845. }
  4846. else {
  4847. Tools.Log = Tools._LogDisabled;
  4848. }
  4849. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4850. Tools.Warn = Tools._WarnEnabled;
  4851. }
  4852. else {
  4853. Tools.Warn = Tools._WarnDisabled;
  4854. }
  4855. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4856. Tools.Error = Tools._ErrorEnabled;
  4857. }
  4858. else {
  4859. Tools.Error = Tools._ErrorDisabled;
  4860. }
  4861. },
  4862. enumerable: true,
  4863. configurable: true
  4864. });
  4865. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4866. get: function () {
  4867. return Tools._PerformanceNoneLogLevel;
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4873. get: function () {
  4874. return Tools._PerformanceUserMarkLogLevel;
  4875. },
  4876. enumerable: true,
  4877. configurable: true
  4878. });
  4879. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4880. get: function () {
  4881. return Tools._PerformanceConsoleLogLevel;
  4882. },
  4883. enumerable: true,
  4884. configurable: true
  4885. });
  4886. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4887. set: function (level) {
  4888. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4889. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4890. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4891. return;
  4892. }
  4893. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4894. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4895. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4896. return;
  4897. }
  4898. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4899. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4900. },
  4901. enumerable: true,
  4902. configurable: true
  4903. });
  4904. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4905. };
  4906. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4907. };
  4908. Tools._StartUserMark = function (counterName, condition) {
  4909. if (condition === void 0) { condition = true; }
  4910. if (!condition || !Tools._performance.mark) {
  4911. return;
  4912. }
  4913. Tools._performance.mark(counterName + "-Begin");
  4914. };
  4915. Tools._EndUserMark = function (counterName, condition) {
  4916. if (condition === void 0) { condition = true; }
  4917. if (!condition || !Tools._performance.mark) {
  4918. return;
  4919. }
  4920. Tools._performance.mark(counterName + "-End");
  4921. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4922. };
  4923. Tools._StartPerformanceConsole = function (counterName, condition) {
  4924. if (condition === void 0) { condition = true; }
  4925. if (!condition) {
  4926. return;
  4927. }
  4928. Tools._StartUserMark(counterName, condition);
  4929. if (console.time) {
  4930. console.time(counterName);
  4931. }
  4932. };
  4933. Tools._EndPerformanceConsole = function (counterName, condition) {
  4934. if (condition === void 0) { condition = true; }
  4935. if (!condition) {
  4936. return;
  4937. }
  4938. Tools._EndUserMark(counterName, condition);
  4939. if (console.time) {
  4940. console.timeEnd(counterName);
  4941. }
  4942. };
  4943. Object.defineProperty(Tools, "Now", {
  4944. get: function () {
  4945. if (window.performance && window.performance.now) {
  4946. return window.performance.now();
  4947. }
  4948. return new Date().getTime();
  4949. },
  4950. enumerable: true,
  4951. configurable: true
  4952. });
  4953. Tools.BaseUrl = "";
  4954. Tools.CorsBehavior = "anonymous";
  4955. Tools.UseFallbackTexture = true;
  4956. // Logs
  4957. Tools._NoneLogLevel = 0;
  4958. Tools._MessageLogLevel = 1;
  4959. Tools._WarningLogLevel = 2;
  4960. Tools._ErrorLogLevel = 4;
  4961. Tools._LogCache = "";
  4962. Tools.errorsCount = 0;
  4963. Tools.Log = Tools._LogEnabled;
  4964. Tools.Warn = Tools._WarnEnabled;
  4965. Tools.Error = Tools._ErrorEnabled;
  4966. // Performances
  4967. Tools._PerformanceNoneLogLevel = 0;
  4968. Tools._PerformanceUserMarkLogLevel = 1;
  4969. Tools._PerformanceConsoleLogLevel = 2;
  4970. Tools._performance = window.performance;
  4971. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4972. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4973. return Tools;
  4974. })();
  4975. BABYLON.Tools = Tools;
  4976. /**
  4977. * An implementation of a loop for asynchronous functions.
  4978. */
  4979. var AsyncLoop = (function () {
  4980. /**
  4981. * Constroctor.
  4982. * @param iterations the number of iterations.
  4983. * @param _fn the function to run each iteration
  4984. * @param _successCallback the callback that will be called upon succesful execution
  4985. * @param offset starting offset.
  4986. */
  4987. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4988. if (offset === void 0) { offset = 0; }
  4989. this.iterations = iterations;
  4990. this._fn = _fn;
  4991. this._successCallback = _successCallback;
  4992. this.index = offset - 1;
  4993. this._done = false;
  4994. }
  4995. /**
  4996. * Execute the next iteration. Must be called after the last iteration was finished.
  4997. */
  4998. AsyncLoop.prototype.executeNext = function () {
  4999. if (!this._done) {
  5000. if (this.index + 1 < this.iterations) {
  5001. ++this.index;
  5002. this._fn(this);
  5003. }
  5004. else {
  5005. this.breakLoop();
  5006. }
  5007. }
  5008. };
  5009. /**
  5010. * Break the loop and run the success callback.
  5011. */
  5012. AsyncLoop.prototype.breakLoop = function () {
  5013. this._done = true;
  5014. this._successCallback();
  5015. };
  5016. /**
  5017. * Helper function
  5018. */
  5019. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5020. if (offset === void 0) { offset = 0; }
  5021. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5022. loop.executeNext();
  5023. return loop;
  5024. };
  5025. /**
  5026. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5027. * @param iterations total number of iterations
  5028. * @param syncedIterations number of synchronous iterations in each async iteration.
  5029. * @param fn the function to call each iteration.
  5030. * @param callback a success call back that will be called when iterating stops.
  5031. * @param breakFunction a break condition (optional)
  5032. * @param timeout timeout settings for the setTimeout function. default - 0.
  5033. * @constructor
  5034. */
  5035. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5036. if (timeout === void 0) { timeout = 0; }
  5037. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5038. if (breakFunction && breakFunction())
  5039. loop.breakLoop();
  5040. else {
  5041. setTimeout(function () {
  5042. for (var i = 0; i < syncedIterations; ++i) {
  5043. var iteration = (loop.index * syncedIterations) + i;
  5044. if (iteration >= iterations)
  5045. break;
  5046. fn(iteration);
  5047. if (breakFunction && breakFunction()) {
  5048. loop.breakLoop();
  5049. break;
  5050. }
  5051. }
  5052. loop.executeNext();
  5053. }, timeout);
  5054. }
  5055. }, callback);
  5056. };
  5057. return AsyncLoop;
  5058. })();
  5059. BABYLON.AsyncLoop = AsyncLoop;
  5060. })(BABYLON || (BABYLON = {}));
  5061. var BABYLON;
  5062. (function (BABYLON) {
  5063. var Internals;
  5064. (function (Internals) {
  5065. var _AlphaState = (function () {
  5066. function _AlphaState() {
  5067. this._isAlphaBlendDirty = false;
  5068. this._isBlendFunctionParametersDirty = false;
  5069. this._alphaBlend = false;
  5070. this._blendFunctionParameters = new Array(4);
  5071. }
  5072. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5073. get: function () {
  5074. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5075. },
  5076. enumerable: true,
  5077. configurable: true
  5078. });
  5079. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5080. get: function () {
  5081. return this._alphaBlend;
  5082. },
  5083. set: function (value) {
  5084. if (this._alphaBlend === value) {
  5085. return;
  5086. }
  5087. this._alphaBlend = value;
  5088. this._isAlphaBlendDirty = true;
  5089. },
  5090. enumerable: true,
  5091. configurable: true
  5092. });
  5093. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5094. if (this._blendFunctionParameters[0] === value0 &&
  5095. this._blendFunctionParameters[1] === value1 &&
  5096. this._blendFunctionParameters[2] === value2 &&
  5097. this._blendFunctionParameters[3] === value3) {
  5098. return;
  5099. }
  5100. this._blendFunctionParameters[0] = value0;
  5101. this._blendFunctionParameters[1] = value1;
  5102. this._blendFunctionParameters[2] = value2;
  5103. this._blendFunctionParameters[3] = value3;
  5104. this._isBlendFunctionParametersDirty = true;
  5105. };
  5106. _AlphaState.prototype.reset = function () {
  5107. this._alphaBlend = false;
  5108. this._blendFunctionParameters[0] = null;
  5109. this._blendFunctionParameters[1] = null;
  5110. this._blendFunctionParameters[2] = null;
  5111. this._blendFunctionParameters[3] = null;
  5112. this._isAlphaBlendDirty = true;
  5113. this._isBlendFunctionParametersDirty = false;
  5114. };
  5115. _AlphaState.prototype.apply = function (gl) {
  5116. if (!this.isDirty) {
  5117. return;
  5118. }
  5119. // Alpha blend
  5120. if (this._isAlphaBlendDirty) {
  5121. if (this._alphaBlend) {
  5122. gl.enable(gl.BLEND);
  5123. }
  5124. else {
  5125. gl.disable(gl.BLEND);
  5126. }
  5127. this._isAlphaBlendDirty = false;
  5128. }
  5129. // Alpha function
  5130. if (this._isBlendFunctionParametersDirty) {
  5131. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5132. this._isBlendFunctionParametersDirty = false;
  5133. }
  5134. };
  5135. return _AlphaState;
  5136. })();
  5137. Internals._AlphaState = _AlphaState;
  5138. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5139. })(BABYLON || (BABYLON = {}));
  5140. var BABYLON;
  5141. (function (BABYLON) {
  5142. var Internals;
  5143. (function (Internals) {
  5144. var _DepthCullingState = (function () {
  5145. function _DepthCullingState() {
  5146. this._isDepthTestDirty = false;
  5147. this._isDepthMaskDirty = false;
  5148. this._isDepthFuncDirty = false;
  5149. this._isCullFaceDirty = false;
  5150. this._isCullDirty = false;
  5151. this._isZOffsetDirty = false;
  5152. }
  5153. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5154. get: function () {
  5155. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5156. },
  5157. enumerable: true,
  5158. configurable: true
  5159. });
  5160. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5161. get: function () {
  5162. return this._zOffset;
  5163. },
  5164. set: function (value) {
  5165. if (this._zOffset === value) {
  5166. return;
  5167. }
  5168. this._zOffset = value;
  5169. this._isZOffsetDirty = true;
  5170. },
  5171. enumerable: true,
  5172. configurable: true
  5173. });
  5174. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5175. get: function () {
  5176. return this._cullFace;
  5177. },
  5178. set: function (value) {
  5179. if (this._cullFace === value) {
  5180. return;
  5181. }
  5182. this._cullFace = value;
  5183. this._isCullFaceDirty = true;
  5184. },
  5185. enumerable: true,
  5186. configurable: true
  5187. });
  5188. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5189. get: function () {
  5190. return this._cull;
  5191. },
  5192. set: function (value) {
  5193. if (this._cull === value) {
  5194. return;
  5195. }
  5196. this._cull = value;
  5197. this._isCullDirty = true;
  5198. },
  5199. enumerable: true,
  5200. configurable: true
  5201. });
  5202. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5203. get: function () {
  5204. return this._depthFunc;
  5205. },
  5206. set: function (value) {
  5207. if (this._depthFunc === value) {
  5208. return;
  5209. }
  5210. this._depthFunc = value;
  5211. this._isDepthFuncDirty = true;
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5217. get: function () {
  5218. return this._depthMask;
  5219. },
  5220. set: function (value) {
  5221. if (this._depthMask === value) {
  5222. return;
  5223. }
  5224. this._depthMask = value;
  5225. this._isDepthMaskDirty = true;
  5226. },
  5227. enumerable: true,
  5228. configurable: true
  5229. });
  5230. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5231. get: function () {
  5232. return this._depthTest;
  5233. },
  5234. set: function (value) {
  5235. if (this._depthTest === value) {
  5236. return;
  5237. }
  5238. this._depthTest = value;
  5239. this._isDepthTestDirty = true;
  5240. },
  5241. enumerable: true,
  5242. configurable: true
  5243. });
  5244. _DepthCullingState.prototype.reset = function () {
  5245. this._depthMask = true;
  5246. this._depthTest = true;
  5247. this._depthFunc = null;
  5248. this._cull = null;
  5249. this._cullFace = null;
  5250. this._zOffset = 0;
  5251. this._isDepthTestDirty = true;
  5252. this._isDepthMaskDirty = true;
  5253. this._isDepthFuncDirty = false;
  5254. this._isCullFaceDirty = false;
  5255. this._isCullDirty = false;
  5256. this._isZOffsetDirty = false;
  5257. };
  5258. _DepthCullingState.prototype.apply = function (gl) {
  5259. if (!this.isDirty) {
  5260. return;
  5261. }
  5262. // Cull
  5263. if (this._isCullDirty) {
  5264. if (this.cull) {
  5265. gl.enable(gl.CULL_FACE);
  5266. }
  5267. else {
  5268. gl.disable(gl.CULL_FACE);
  5269. }
  5270. this._isCullDirty = false;
  5271. }
  5272. // Cull face
  5273. if (this._isCullFaceDirty) {
  5274. gl.cullFace(this.cullFace);
  5275. this._isCullFaceDirty = false;
  5276. }
  5277. // Depth mask
  5278. if (this._isDepthMaskDirty) {
  5279. gl.depthMask(this.depthMask);
  5280. this._isDepthMaskDirty = false;
  5281. }
  5282. // Depth test
  5283. if (this._isDepthTestDirty) {
  5284. if (this.depthTest) {
  5285. gl.enable(gl.DEPTH_TEST);
  5286. }
  5287. else {
  5288. gl.disable(gl.DEPTH_TEST);
  5289. }
  5290. this._isDepthTestDirty = false;
  5291. }
  5292. // Depth func
  5293. if (this._isDepthFuncDirty) {
  5294. gl.depthFunc(this.depthFunc);
  5295. this._isDepthFuncDirty = false;
  5296. }
  5297. // zOffset
  5298. if (this._isZOffsetDirty) {
  5299. if (this.zOffset) {
  5300. gl.enable(gl.POLYGON_OFFSET_FILL);
  5301. gl.polygonOffset(this.zOffset, 0);
  5302. }
  5303. else {
  5304. gl.disable(gl.POLYGON_OFFSET_FILL);
  5305. }
  5306. this._isZOffsetDirty = false;
  5307. }
  5308. };
  5309. return _DepthCullingState;
  5310. })();
  5311. Internals._DepthCullingState = _DepthCullingState;
  5312. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5313. })(BABYLON || (BABYLON = {}));
  5314. var BABYLON;
  5315. (function (BABYLON) {
  5316. var compileShader = function (gl, source, type, defines) {
  5317. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5318. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5319. gl.compileShader(shader);
  5320. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5321. throw new Error(gl.getShaderInfoLog(shader));
  5322. }
  5323. return shader;
  5324. };
  5325. var getWebGLTextureType = function (gl, type) {
  5326. var textureType = gl.UNSIGNED_BYTE;
  5327. if (type === Engine.TEXTURETYPE_FLOAT)
  5328. textureType = gl.FLOAT;
  5329. return textureType;
  5330. };
  5331. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5332. var magFilter = gl.NEAREST;
  5333. var minFilter = gl.NEAREST;
  5334. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5335. magFilter = gl.LINEAR;
  5336. if (generateMipMaps) {
  5337. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5338. }
  5339. else {
  5340. minFilter = gl.LINEAR;
  5341. }
  5342. }
  5343. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5344. magFilter = gl.LINEAR;
  5345. if (generateMipMaps) {
  5346. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5347. }
  5348. else {
  5349. minFilter = gl.LINEAR;
  5350. }
  5351. }
  5352. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5353. magFilter = gl.NEAREST;
  5354. if (generateMipMaps) {
  5355. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5356. }
  5357. else {
  5358. minFilter = gl.NEAREST;
  5359. }
  5360. }
  5361. return {
  5362. min: minFilter,
  5363. mag: magFilter
  5364. };
  5365. };
  5366. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5368. var engine = scene.getEngine();
  5369. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5370. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5371. gl.bindTexture(gl.TEXTURE_2D, texture);
  5372. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5373. texture._baseWidth = width;
  5374. texture._baseHeight = height;
  5375. texture._width = potWidth;
  5376. texture._height = potHeight;
  5377. texture.isReady = true;
  5378. processFunction(potWidth, potHeight);
  5379. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5381. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5382. if (!noMipmap && !isCompressed) {
  5383. gl.generateMipmap(gl.TEXTURE_2D);
  5384. }
  5385. gl.bindTexture(gl.TEXTURE_2D, null);
  5386. engine.resetTextureCache();
  5387. scene._removePendingData(texture);
  5388. if (onLoad) {
  5389. onLoad();
  5390. }
  5391. };
  5392. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5393. var img;
  5394. var onload = function () {
  5395. loadedImages[index] = img;
  5396. loadedImages._internalCount++;
  5397. scene._removePendingData(img);
  5398. if (loadedImages._internalCount === 6) {
  5399. onfinish(loadedImages);
  5400. }
  5401. };
  5402. var onerror = function () {
  5403. scene._removePendingData(img);
  5404. };
  5405. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5406. scene._addPendingData(img);
  5407. };
  5408. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5409. var loadedImages = [];
  5410. loadedImages._internalCount = 0;
  5411. for (var index = 0; index < 6; index++) {
  5412. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5413. }
  5414. };
  5415. var EngineCapabilities = (function () {
  5416. function EngineCapabilities() {
  5417. }
  5418. return EngineCapabilities;
  5419. })();
  5420. BABYLON.EngineCapabilities = EngineCapabilities;
  5421. /**
  5422. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5423. */
  5424. var Engine = (function () {
  5425. /**
  5426. * @constructor
  5427. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5428. * @param {boolean} [antialias] - enable antialias
  5429. * @param options - further options to be sent to the getContext function
  5430. */
  5431. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5432. var _this = this;
  5433. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5434. // Public members
  5435. this.isFullscreen = false;
  5436. this.isPointerLock = false;
  5437. this.cullBackFaces = true;
  5438. this.renderEvenInBackground = true;
  5439. // To enable/disable IDB support and avoid XHR on .manifest
  5440. this.enableOfflineSupport = true;
  5441. this.scenes = new Array();
  5442. this._windowIsBackground = false;
  5443. this._webGLVersion = "1.0";
  5444. this._drawCalls = 0;
  5445. this._renderingQueueLaunched = false;
  5446. this._activeRenderLoops = [];
  5447. // FPS
  5448. this.fpsRange = 60;
  5449. this.previousFramesDuration = [];
  5450. this.fps = 60;
  5451. this.deltaTime = 0;
  5452. // States
  5453. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5454. this._alphaState = new BABYLON.Internals._AlphaState();
  5455. this._alphaMode = Engine.ALPHA_DISABLE;
  5456. // Cache
  5457. this._loadedTexturesCache = new Array();
  5458. this._maxTextureChannels = 16;
  5459. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5460. this._compiledEffects = {};
  5461. this._uintIndicesCurrentlySet = false;
  5462. this._renderingCanvas = canvas;
  5463. options = options || {};
  5464. options.antialias = antialias;
  5465. if (options.preserveDrawingBuffer === undefined) {
  5466. options.preserveDrawingBuffer = false;
  5467. }
  5468. // GL
  5469. //try {
  5470. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5471. // if (this._gl) {
  5472. // this._webGLVersion = "2.0";
  5473. // }
  5474. //} catch (e) {
  5475. // // Do nothing
  5476. //}
  5477. if (!this._gl) {
  5478. try {
  5479. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5480. }
  5481. catch (e) {
  5482. throw new Error("WebGL not supported");
  5483. }
  5484. }
  5485. if (!this._gl) {
  5486. throw new Error("WebGL not supported");
  5487. }
  5488. this._onBlur = function () {
  5489. _this._windowIsBackground = true;
  5490. };
  5491. this._onFocus = function () {
  5492. _this._windowIsBackground = false;
  5493. };
  5494. window.addEventListener("blur", this._onBlur);
  5495. window.addEventListener("focus", this._onFocus);
  5496. // Viewport
  5497. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5498. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5499. this.resize();
  5500. // Caps
  5501. this._caps = new EngineCapabilities();
  5502. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5503. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5504. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5505. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5506. // Infos
  5507. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5508. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5509. if (rendererInfo != null) {
  5510. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5511. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5512. }
  5513. if (!this._glVendor) {
  5514. this._glVendor = "Unknown vendor";
  5515. }
  5516. if (!this._glRenderer) {
  5517. this._glRenderer = "Unknown renderer";
  5518. }
  5519. // Extensions
  5520. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5521. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5522. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5523. 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');
  5524. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5525. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5526. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5527. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5528. this._caps.highPrecisionShaderSupported = true;
  5529. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5530. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5531. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5532. if (this._gl.getShaderPrecisionFormat) {
  5533. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5534. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5535. }
  5536. // Depth buffer
  5537. this.setDepthBuffer(true);
  5538. this.setDepthFunctionToLessOrEqual();
  5539. this.setDepthWrite(true);
  5540. // Fullscreen
  5541. this._onFullscreenChange = function () {
  5542. if (document.fullscreen !== undefined) {
  5543. _this.isFullscreen = document.fullscreen;
  5544. }
  5545. else if (document.mozFullScreen !== undefined) {
  5546. _this.isFullscreen = document.mozFullScreen;
  5547. }
  5548. else if (document.webkitIsFullScreen !== undefined) {
  5549. _this.isFullscreen = document.webkitIsFullScreen;
  5550. }
  5551. else if (document.msIsFullScreen !== undefined) {
  5552. _this.isFullscreen = document.msIsFullScreen;
  5553. }
  5554. // Pointer lock
  5555. if (_this.isFullscreen && _this._pointerLockRequested) {
  5556. canvas.requestPointerLock = canvas.requestPointerLock ||
  5557. canvas.msRequestPointerLock ||
  5558. canvas.mozRequestPointerLock ||
  5559. canvas.webkitRequestPointerLock;
  5560. if (canvas.requestPointerLock) {
  5561. canvas.requestPointerLock();
  5562. }
  5563. }
  5564. };
  5565. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5566. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5567. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5568. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5569. // Pointer lock
  5570. this._onPointerLockChange = function () {
  5571. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5572. document.webkitPointerLockElement === canvas ||
  5573. document.msPointerLockElement === canvas ||
  5574. document.pointerLockElement === canvas);
  5575. };
  5576. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5577. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5578. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5579. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5580. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5581. Engine.audioEngine = new BABYLON.AudioEngine();
  5582. }
  5583. //default loading screen
  5584. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5585. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5586. }
  5587. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5588. get: function () {
  5589. return Engine._ALPHA_DISABLE;
  5590. },
  5591. enumerable: true,
  5592. configurable: true
  5593. });
  5594. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5595. get: function () {
  5596. return Engine._ALPHA_ONEONE;
  5597. },
  5598. enumerable: true,
  5599. configurable: true
  5600. });
  5601. Object.defineProperty(Engine, "ALPHA_ADD", {
  5602. get: function () {
  5603. return Engine._ALPHA_ADD;
  5604. },
  5605. enumerable: true,
  5606. configurable: true
  5607. });
  5608. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5609. get: function () {
  5610. return Engine._ALPHA_COMBINE;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5616. get: function () {
  5617. return Engine._ALPHA_SUBTRACT;
  5618. },
  5619. enumerable: true,
  5620. configurable: true
  5621. });
  5622. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5623. get: function () {
  5624. return Engine._ALPHA_MULTIPLY;
  5625. },
  5626. enumerable: true,
  5627. configurable: true
  5628. });
  5629. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5630. get: function () {
  5631. return Engine._ALPHA_MAXIMIZED;
  5632. },
  5633. enumerable: true,
  5634. configurable: true
  5635. });
  5636. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5637. get: function () {
  5638. return Engine._DELAYLOADSTATE_NONE;
  5639. },
  5640. enumerable: true,
  5641. configurable: true
  5642. });
  5643. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5644. get: function () {
  5645. return Engine._DELAYLOADSTATE_LOADED;
  5646. },
  5647. enumerable: true,
  5648. configurable: true
  5649. });
  5650. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5651. get: function () {
  5652. return Engine._DELAYLOADSTATE_LOADING;
  5653. },
  5654. enumerable: true,
  5655. configurable: true
  5656. });
  5657. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5658. get: function () {
  5659. return Engine._DELAYLOADSTATE_NOTLOADED;
  5660. },
  5661. enumerable: true,
  5662. configurable: true
  5663. });
  5664. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5665. get: function () {
  5666. return Engine._TEXTUREFORMAT_ALPHA;
  5667. },
  5668. enumerable: true,
  5669. configurable: true
  5670. });
  5671. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5672. get: function () {
  5673. return Engine._TEXTUREFORMAT_LUMINANCE;
  5674. },
  5675. enumerable: true,
  5676. configurable: true
  5677. });
  5678. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5679. get: function () {
  5680. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5681. },
  5682. enumerable: true,
  5683. configurable: true
  5684. });
  5685. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5686. get: function () {
  5687. return Engine._TEXTUREFORMAT_RGB;
  5688. },
  5689. enumerable: true,
  5690. configurable: true
  5691. });
  5692. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5693. get: function () {
  5694. return Engine._TEXTUREFORMAT_RGBA;
  5695. },
  5696. enumerable: true,
  5697. configurable: true
  5698. });
  5699. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5700. get: function () {
  5701. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5702. },
  5703. enumerable: true,
  5704. configurable: true
  5705. });
  5706. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5707. get: function () {
  5708. return Engine._TEXTURETYPE_FLOAT;
  5709. },
  5710. enumerable: true,
  5711. configurable: true
  5712. });
  5713. Object.defineProperty(Engine, "Version", {
  5714. get: function () {
  5715. return "2.4.0-alpha";
  5716. },
  5717. enumerable: true,
  5718. configurable: true
  5719. });
  5720. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5721. get: function () {
  5722. return this._webGLVersion;
  5723. },
  5724. enumerable: true,
  5725. configurable: true
  5726. });
  5727. Engine.prototype._prepareWorkingCanvas = function () {
  5728. if (this._workingCanvas) {
  5729. return;
  5730. }
  5731. this._workingCanvas = document.createElement("canvas");
  5732. this._workingContext = this._workingCanvas.getContext("2d");
  5733. };
  5734. Engine.prototype.resetTextureCache = function () {
  5735. for (var index = 0; index < this._maxTextureChannels; index++) {
  5736. this._activeTexturesCache[index] = null;
  5737. }
  5738. };
  5739. Engine.prototype.getGlInfo = function () {
  5740. return {
  5741. vendor: this._glVendor,
  5742. renderer: this._glRenderer,
  5743. version: this._glVersion
  5744. };
  5745. };
  5746. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5747. if (useScreen === void 0) { useScreen = false; }
  5748. var viewport = camera.viewport;
  5749. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5750. };
  5751. Engine.prototype.getRenderWidth = function (useScreen) {
  5752. if (useScreen === void 0) { useScreen = false; }
  5753. if (!useScreen && this._currentRenderTarget) {
  5754. return this._currentRenderTarget._width;
  5755. }
  5756. return this._renderingCanvas.width;
  5757. };
  5758. Engine.prototype.getRenderHeight = function (useScreen) {
  5759. if (useScreen === void 0) { useScreen = false; }
  5760. if (!useScreen && this._currentRenderTarget) {
  5761. return this._currentRenderTarget._height;
  5762. }
  5763. return this._renderingCanvas.height;
  5764. };
  5765. Engine.prototype.getRenderingCanvas = function () {
  5766. return this._renderingCanvas;
  5767. };
  5768. Engine.prototype.getRenderingCanvasClientRect = function () {
  5769. return this._renderingCanvas.getBoundingClientRect();
  5770. };
  5771. Engine.prototype.setHardwareScalingLevel = function (level) {
  5772. this._hardwareScalingLevel = level;
  5773. this.resize();
  5774. };
  5775. Engine.prototype.getHardwareScalingLevel = function () {
  5776. return this._hardwareScalingLevel;
  5777. };
  5778. Engine.prototype.getLoadedTexturesCache = function () {
  5779. return this._loadedTexturesCache;
  5780. };
  5781. Engine.prototype.getCaps = function () {
  5782. return this._caps;
  5783. };
  5784. Object.defineProperty(Engine.prototype, "drawCalls", {
  5785. get: function () {
  5786. return this._drawCalls;
  5787. },
  5788. enumerable: true,
  5789. configurable: true
  5790. });
  5791. // Methods
  5792. Engine.prototype.resetDrawCalls = function () {
  5793. this._drawCalls = 0;
  5794. };
  5795. Engine.prototype.setDepthFunctionToGreater = function () {
  5796. this._depthCullingState.depthFunc = this._gl.GREATER;
  5797. };
  5798. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5799. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5800. };
  5801. Engine.prototype.setDepthFunctionToLess = function () {
  5802. this._depthCullingState.depthFunc = this._gl.LESS;
  5803. };
  5804. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5805. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5806. };
  5807. /**
  5808. * stop executing a render loop function and remove it from the execution array
  5809. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5810. */
  5811. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5812. if (!renderFunction) {
  5813. this._activeRenderLoops = [];
  5814. return;
  5815. }
  5816. var index = this._activeRenderLoops.indexOf(renderFunction);
  5817. if (index >= 0) {
  5818. this._activeRenderLoops.splice(index, 1);
  5819. }
  5820. };
  5821. Engine.prototype._renderLoop = function () {
  5822. var shouldRender = true;
  5823. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5824. shouldRender = false;
  5825. }
  5826. if (shouldRender) {
  5827. // Start new frame
  5828. this.beginFrame();
  5829. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5830. var renderFunction = this._activeRenderLoops[index];
  5831. renderFunction();
  5832. }
  5833. // Present
  5834. this.endFrame();
  5835. }
  5836. if (this._activeRenderLoops.length > 0) {
  5837. // Register new frame
  5838. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5839. }
  5840. else {
  5841. this._renderingQueueLaunched = false;
  5842. }
  5843. };
  5844. /**
  5845. * Register and execute a render loop. The engine can have more than one render function.
  5846. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5847. * @example
  5848. * engine.runRenderLoop(function () {
  5849. * scene.render()
  5850. * })
  5851. */
  5852. Engine.prototype.runRenderLoop = function (renderFunction) {
  5853. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5854. return;
  5855. }
  5856. this._activeRenderLoops.push(renderFunction);
  5857. if (!this._renderingQueueLaunched) {
  5858. this._renderingQueueLaunched = true;
  5859. this._bindedRenderFunction = this._renderLoop.bind(this);
  5860. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5861. }
  5862. };
  5863. /**
  5864. * Toggle full screen mode.
  5865. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5866. */
  5867. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5868. if (this.isFullscreen) {
  5869. BABYLON.Tools.ExitFullscreen();
  5870. }
  5871. else {
  5872. this._pointerLockRequested = requestPointerLock;
  5873. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5874. }
  5875. };
  5876. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5877. this.applyStates();
  5878. if (backBuffer) {
  5879. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5880. }
  5881. if (depthStencil && this._depthCullingState.depthMask) {
  5882. this._gl.clearDepth(1.0);
  5883. }
  5884. var mode = 0;
  5885. if (backBuffer) {
  5886. mode |= this._gl.COLOR_BUFFER_BIT;
  5887. }
  5888. if (depthStencil && this._depthCullingState.depthMask) {
  5889. mode |= this._gl.DEPTH_BUFFER_BIT;
  5890. }
  5891. this._gl.clear(mode);
  5892. };
  5893. /**
  5894. * Set the WebGL's viewport
  5895. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5896. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5897. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5898. */
  5899. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5900. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5901. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5902. var x = viewport.x || 0;
  5903. var y = viewport.y || 0;
  5904. this._cachedViewport = viewport;
  5905. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5906. };
  5907. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5908. this._cachedViewport = null;
  5909. this._gl.viewport(x, y, width, height);
  5910. };
  5911. Engine.prototype.beginFrame = function () {
  5912. this._measureFps();
  5913. };
  5914. Engine.prototype.endFrame = function () {
  5915. //this.flushFramebuffer();
  5916. };
  5917. /**
  5918. * resize the view according to the canvas' size.
  5919. * @example
  5920. * window.addEventListener("resize", function () {
  5921. * engine.resize();
  5922. * });
  5923. */
  5924. Engine.prototype.resize = function () {
  5925. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5926. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5927. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5928. for (var index = 0; index < this.scenes.length; index++) {
  5929. var scene = this.scenes[index];
  5930. if (scene.debugLayer.isVisible()) {
  5931. scene.debugLayer._syncPositions();
  5932. }
  5933. }
  5934. };
  5935. /**
  5936. * force a specific size of the canvas
  5937. * @param {number} width - the new canvas' width
  5938. * @param {number} height - the new canvas' height
  5939. */
  5940. Engine.prototype.setSize = function (width, height) {
  5941. this._renderingCanvas.width = width;
  5942. this._renderingCanvas.height = height;
  5943. for (var index = 0; index < this.scenes.length; index++) {
  5944. var scene = this.scenes[index];
  5945. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5946. var cam = scene.cameras[camIndex];
  5947. cam._currentRenderId = 0;
  5948. }
  5949. }
  5950. };
  5951. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5952. this._currentRenderTarget = texture;
  5953. var gl = this._gl;
  5954. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5955. if (texture.isCube) {
  5956. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5957. }
  5958. else {
  5959. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5960. }
  5961. this._gl.viewport(0, 0, texture._width, texture._height);
  5962. this.wipeCaches();
  5963. };
  5964. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5965. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5966. this._currentRenderTarget = null;
  5967. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5968. var gl = this._gl;
  5969. gl.bindTexture(gl.TEXTURE_2D, texture);
  5970. gl.generateMipmap(gl.TEXTURE_2D);
  5971. gl.bindTexture(gl.TEXTURE_2D, null);
  5972. }
  5973. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5974. };
  5975. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5976. if (texture.generateMipMaps) {
  5977. var gl = this._gl;
  5978. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5979. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5980. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5981. }
  5982. };
  5983. Engine.prototype.flushFramebuffer = function () {
  5984. this._gl.flush();
  5985. };
  5986. Engine.prototype.restoreDefaultFramebuffer = function () {
  5987. this._currentRenderTarget = null;
  5988. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5989. this.setViewport(this._cachedViewport);
  5990. this.wipeCaches();
  5991. };
  5992. // VBOs
  5993. Engine.prototype._resetVertexBufferBinding = function () {
  5994. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5995. this._cachedVertexBuffers = null;
  5996. };
  5997. Engine.prototype.createVertexBuffer = function (vertices) {
  5998. var vbo = this._gl.createBuffer();
  5999. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6000. if (vertices instanceof Float32Array) {
  6001. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6002. }
  6003. else {
  6004. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6005. }
  6006. this._resetVertexBufferBinding();
  6007. vbo.references = 1;
  6008. return vbo;
  6009. };
  6010. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6011. var vbo = this._gl.createBuffer();
  6012. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6013. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6014. this._resetVertexBufferBinding();
  6015. vbo.references = 1;
  6016. return vbo;
  6017. };
  6018. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6019. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6020. if (offset === undefined) {
  6021. offset = 0;
  6022. }
  6023. if (vertices instanceof Float32Array) {
  6024. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6025. }
  6026. else {
  6027. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6028. }
  6029. this._resetVertexBufferBinding();
  6030. };
  6031. Engine.prototype._resetIndexBufferBinding = function () {
  6032. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6033. this._cachedIndexBuffer = null;
  6034. };
  6035. Engine.prototype.createIndexBuffer = function (indices) {
  6036. var vbo = this._gl.createBuffer();
  6037. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6038. // Check for 32 bits indices
  6039. var arrayBuffer;
  6040. var need32Bits = false;
  6041. if (this._caps.uintIndices) {
  6042. for (var index = 0; index < indices.length; index++) {
  6043. if (indices[index] > 65535) {
  6044. need32Bits = true;
  6045. break;
  6046. }
  6047. }
  6048. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6049. }
  6050. else {
  6051. arrayBuffer = new Uint16Array(indices);
  6052. }
  6053. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6054. this._resetIndexBufferBinding();
  6055. vbo.references = 1;
  6056. vbo.is32Bits = need32Bits;
  6057. return vbo;
  6058. };
  6059. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6060. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6061. this._cachedVertexBuffers = vertexBuffer;
  6062. this._cachedEffectForVertexBuffers = effect;
  6063. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6064. var offset = 0;
  6065. for (var index = 0; index < vertexDeclaration.length; index++) {
  6066. var order = effect.getAttributeLocation(index);
  6067. if (order >= 0) {
  6068. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6069. }
  6070. offset += vertexDeclaration[index] * 4;
  6071. }
  6072. }
  6073. if (this._cachedIndexBuffer !== indexBuffer) {
  6074. this._cachedIndexBuffer = indexBuffer;
  6075. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6076. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6077. }
  6078. };
  6079. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6080. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6081. this._cachedVertexBuffers = vertexBuffers;
  6082. this._cachedEffectForVertexBuffers = effect;
  6083. var attributes = effect.getAttributesNames();
  6084. for (var index = 0; index < attributes.length; index++) {
  6085. var order = effect.getAttributeLocation(index);
  6086. if (order >= 0) {
  6087. var vertexBuffer = vertexBuffers[attributes[index]];
  6088. if (!vertexBuffer) {
  6089. continue;
  6090. }
  6091. var stride = vertexBuffer.getStrideSize();
  6092. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6093. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6094. }
  6095. }
  6096. }
  6097. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6098. this._cachedIndexBuffer = indexBuffer;
  6099. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6100. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6101. }
  6102. };
  6103. Engine.prototype._releaseBuffer = function (buffer) {
  6104. buffer.references--;
  6105. if (buffer.references === 0) {
  6106. this._gl.deleteBuffer(buffer);
  6107. return true;
  6108. }
  6109. return false;
  6110. };
  6111. Engine.prototype.createInstancesBuffer = function (capacity) {
  6112. var buffer = this._gl.createBuffer();
  6113. buffer.capacity = capacity;
  6114. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6115. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6116. return buffer;
  6117. };
  6118. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6119. this._gl.deleteBuffer(buffer);
  6120. };
  6121. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6122. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6123. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6124. for (var index = 0; index < 4; index++) {
  6125. var offsetLocation = offsetLocations[index];
  6126. this._gl.enableVertexAttribArray(offsetLocation);
  6127. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6128. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6129. }
  6130. };
  6131. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6132. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6133. for (var index = 0; index < 4; index++) {
  6134. var offsetLocation = offsetLocations[index];
  6135. this._gl.disableVertexAttribArray(offsetLocation);
  6136. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6137. }
  6138. };
  6139. Engine.prototype.applyStates = function () {
  6140. this._depthCullingState.apply(this._gl);
  6141. this._alphaState.apply(this._gl);
  6142. };
  6143. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6144. // Apply states
  6145. this.applyStates();
  6146. this._drawCalls++;
  6147. // Render
  6148. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6149. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6150. if (instancesCount) {
  6151. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6152. return;
  6153. }
  6154. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6155. };
  6156. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6157. // Apply states
  6158. this.applyStates();
  6159. this._drawCalls++;
  6160. if (instancesCount) {
  6161. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6162. return;
  6163. }
  6164. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6165. };
  6166. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6167. // Apply states
  6168. this.applyStates();
  6169. this._drawCalls++;
  6170. if (instancesCount) {
  6171. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6172. return;
  6173. }
  6174. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6175. };
  6176. // Shaders
  6177. Engine.prototype._releaseEffect = function (effect) {
  6178. if (this._compiledEffects[effect._key]) {
  6179. delete this._compiledEffects[effect._key];
  6180. if (effect.getProgram()) {
  6181. this._gl.deleteProgram(effect.getProgram());
  6182. }
  6183. }
  6184. };
  6185. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6186. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6187. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6188. var name = vertex + "+" + fragment + "@" + defines;
  6189. if (this._compiledEffects[name]) {
  6190. return this._compiledEffects[name];
  6191. }
  6192. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6193. effect._key = name;
  6194. this._compiledEffects[name] = effect;
  6195. return effect;
  6196. };
  6197. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6198. if (uniformsNames === void 0) { uniformsNames = []; }
  6199. if (samplers === void 0) { samplers = []; }
  6200. if (defines === void 0) { defines = ""; }
  6201. return this.createEffect({
  6202. vertex: "particles",
  6203. fragmentElement: fragmentName
  6204. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6205. };
  6206. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6207. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6208. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6209. var shaderProgram = this._gl.createProgram();
  6210. this._gl.attachShader(shaderProgram, vertexShader);
  6211. this._gl.attachShader(shaderProgram, fragmentShader);
  6212. this._gl.linkProgram(shaderProgram);
  6213. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6214. if (!linked) {
  6215. var error = this._gl.getProgramInfoLog(shaderProgram);
  6216. if (error) {
  6217. throw new Error(error);
  6218. }
  6219. }
  6220. this._gl.deleteShader(vertexShader);
  6221. this._gl.deleteShader(fragmentShader);
  6222. return shaderProgram;
  6223. };
  6224. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6225. var results = [];
  6226. for (var index = 0; index < uniformsNames.length; index++) {
  6227. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6228. }
  6229. return results;
  6230. };
  6231. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6232. var results = [];
  6233. for (var index = 0; index < attributesNames.length; index++) {
  6234. try {
  6235. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6236. }
  6237. catch (e) {
  6238. results.push(-1);
  6239. }
  6240. }
  6241. return results;
  6242. };
  6243. Engine.prototype.enableEffect = function (effect) {
  6244. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6245. if (effect && effect.onBind) {
  6246. effect.onBind(effect);
  6247. }
  6248. return;
  6249. }
  6250. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6251. // Use program
  6252. this._gl.useProgram(effect.getProgram());
  6253. for (var i in this._vertexAttribArrays) {
  6254. //make sure this is a number)
  6255. var iAsNumber = +i;
  6256. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6257. continue;
  6258. }
  6259. this._vertexAttribArrays[iAsNumber] = false;
  6260. this._gl.disableVertexAttribArray(iAsNumber);
  6261. }
  6262. var attributesCount = effect.getAttributesCount();
  6263. for (var index = 0; index < attributesCount; index++) {
  6264. // Attributes
  6265. var order = effect.getAttributeLocation(index);
  6266. if (order >= 0) {
  6267. this._vertexAttribArrays[order] = true;
  6268. this._gl.enableVertexAttribArray(order);
  6269. }
  6270. }
  6271. this._currentEffect = effect;
  6272. if (effect.onBind) {
  6273. effect.onBind(effect);
  6274. }
  6275. };
  6276. Engine.prototype.setArray = function (uniform, array) {
  6277. if (!uniform)
  6278. return;
  6279. this._gl.uniform1fv(uniform, array);
  6280. };
  6281. Engine.prototype.setArray2 = function (uniform, array) {
  6282. if (!uniform || array.length % 2 !== 0)
  6283. return;
  6284. this._gl.uniform2fv(uniform, array);
  6285. };
  6286. Engine.prototype.setArray3 = function (uniform, array) {
  6287. if (!uniform || array.length % 3 !== 0)
  6288. return;
  6289. this._gl.uniform3fv(uniform, array);
  6290. };
  6291. Engine.prototype.setArray4 = function (uniform, array) {
  6292. if (!uniform || array.length % 4 !== 0)
  6293. return;
  6294. this._gl.uniform4fv(uniform, array);
  6295. };
  6296. Engine.prototype.setMatrices = function (uniform, matrices) {
  6297. if (!uniform)
  6298. return;
  6299. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6300. };
  6301. Engine.prototype.setMatrix = function (uniform, matrix) {
  6302. if (!uniform)
  6303. return;
  6304. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6305. };
  6306. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6307. if (!uniform)
  6308. return;
  6309. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6310. };
  6311. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6312. if (!uniform)
  6313. return;
  6314. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6315. };
  6316. Engine.prototype.setFloat = function (uniform, value) {
  6317. if (!uniform)
  6318. return;
  6319. this._gl.uniform1f(uniform, value);
  6320. };
  6321. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6322. if (!uniform)
  6323. return;
  6324. this._gl.uniform2f(uniform, x, y);
  6325. };
  6326. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6327. if (!uniform)
  6328. return;
  6329. this._gl.uniform3f(uniform, x, y, z);
  6330. };
  6331. Engine.prototype.setBool = function (uniform, bool) {
  6332. if (!uniform)
  6333. return;
  6334. this._gl.uniform1i(uniform, bool);
  6335. };
  6336. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6337. if (!uniform)
  6338. return;
  6339. this._gl.uniform4f(uniform, x, y, z, w);
  6340. };
  6341. Engine.prototype.setColor3 = function (uniform, color3) {
  6342. if (!uniform)
  6343. return;
  6344. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6345. };
  6346. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6347. if (!uniform)
  6348. return;
  6349. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6350. };
  6351. // States
  6352. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6353. if (zOffset === void 0) { zOffset = 0; }
  6354. if (reverseSide === void 0) { reverseSide = false; }
  6355. // Culling
  6356. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6357. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6358. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6359. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6360. if (culling) {
  6361. this._depthCullingState.cullFace = cullFace;
  6362. this._depthCullingState.cull = true;
  6363. }
  6364. else {
  6365. this._depthCullingState.cull = false;
  6366. }
  6367. }
  6368. // Z offset
  6369. this._depthCullingState.zOffset = zOffset;
  6370. };
  6371. Engine.prototype.setDepthBuffer = function (enable) {
  6372. this._depthCullingState.depthTest = enable;
  6373. };
  6374. Engine.prototype.getDepthWrite = function () {
  6375. return this._depthCullingState.depthMask;
  6376. };
  6377. Engine.prototype.setDepthWrite = function (enable) {
  6378. this._depthCullingState.depthMask = enable;
  6379. };
  6380. Engine.prototype.setColorWrite = function (enable) {
  6381. this._gl.colorMask(enable, enable, enable, enable);
  6382. };
  6383. Engine.prototype.setAlphaMode = function (mode) {
  6384. if (this._alphaMode === mode) {
  6385. return;
  6386. }
  6387. switch (mode) {
  6388. case Engine.ALPHA_DISABLE:
  6389. this.setDepthWrite(true);
  6390. this._alphaState.alphaBlend = false;
  6391. break;
  6392. case Engine.ALPHA_COMBINE:
  6393. this.setDepthWrite(false);
  6394. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6395. this._alphaState.alphaBlend = true;
  6396. break;
  6397. case Engine.ALPHA_ONEONE:
  6398. this.setDepthWrite(false);
  6399. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6400. this._alphaState.alphaBlend = true;
  6401. break;
  6402. case Engine.ALPHA_ADD:
  6403. this.setDepthWrite(false);
  6404. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6405. this._alphaState.alphaBlend = true;
  6406. break;
  6407. case Engine.ALPHA_SUBTRACT:
  6408. this.setDepthWrite(false);
  6409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6410. this._alphaState.alphaBlend = true;
  6411. break;
  6412. case Engine.ALPHA_MULTIPLY:
  6413. this.setDepthWrite(false);
  6414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6415. this._alphaState.alphaBlend = true;
  6416. break;
  6417. case Engine.ALPHA_MAXIMIZED:
  6418. this.setDepthWrite(false);
  6419. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6420. this._alphaState.alphaBlend = true;
  6421. break;
  6422. }
  6423. this._alphaMode = mode;
  6424. };
  6425. Engine.prototype.getAlphaMode = function () {
  6426. return this._alphaMode;
  6427. };
  6428. Engine.prototype.setAlphaTesting = function (enable) {
  6429. this._alphaTest = enable;
  6430. };
  6431. Engine.prototype.getAlphaTesting = function () {
  6432. return this._alphaTest;
  6433. };
  6434. // Textures
  6435. Engine.prototype.wipeCaches = function () {
  6436. this.resetTextureCache();
  6437. this._currentEffect = null;
  6438. this._depthCullingState.reset();
  6439. this._alphaState.reset();
  6440. this._cachedVertexBuffers = null;
  6441. this._cachedIndexBuffer = null;
  6442. this._cachedEffectForVertexBuffers = null;
  6443. };
  6444. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6445. var gl = this._gl;
  6446. gl.bindTexture(gl.TEXTURE_2D, texture);
  6447. var magFilter = gl.NEAREST;
  6448. var minFilter = gl.NEAREST;
  6449. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6450. magFilter = gl.LINEAR;
  6451. minFilter = gl.LINEAR;
  6452. }
  6453. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6454. magFilter = gl.LINEAR;
  6455. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6456. }
  6457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6459. gl.bindTexture(gl.TEXTURE_2D, null);
  6460. texture.samplingMode = samplingMode;
  6461. };
  6462. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6463. var _this = this;
  6464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6465. if (onLoad === void 0) { onLoad = null; }
  6466. if (onError === void 0) { onError = null; }
  6467. if (buffer === void 0) { buffer = null; }
  6468. var texture = this._gl.createTexture();
  6469. var extension;
  6470. var fromData = false;
  6471. if (url.substr(0, 5) === "data:") {
  6472. fromData = true;
  6473. }
  6474. if (!fromData)
  6475. extension = url.substr(url.length - 4, 4).toLowerCase();
  6476. else {
  6477. var oldUrl = url;
  6478. fromData = oldUrl.split(':');
  6479. url = oldUrl;
  6480. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6481. }
  6482. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6483. var isTGA = (extension === ".tga");
  6484. scene._addPendingData(texture);
  6485. texture.url = url;
  6486. texture.noMipmap = noMipmap;
  6487. texture.references = 1;
  6488. texture.samplingMode = samplingMode;
  6489. this._loadedTexturesCache.push(texture);
  6490. var onerror = function () {
  6491. scene._removePendingData(texture);
  6492. if (onError) {
  6493. onError();
  6494. }
  6495. };
  6496. var callback;
  6497. if (isTGA) {
  6498. callback = function (arrayBuffer) {
  6499. var data = new Uint8Array(arrayBuffer);
  6500. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6501. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6502. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6503. }, onLoad, samplingMode);
  6504. };
  6505. if (!(fromData instanceof Array))
  6506. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6507. callback(arrayBuffer);
  6508. }, onerror, scene.database, true);
  6509. else
  6510. callback(buffer);
  6511. }
  6512. else if (isDDS) {
  6513. callback = function (data) {
  6514. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6515. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6516. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6517. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6518. }, onLoad, samplingMode);
  6519. };
  6520. if (!(fromData instanceof Array))
  6521. BABYLON.Tools.LoadFile(url, function (data) {
  6522. callback(data);
  6523. }, onerror, scene.database, true);
  6524. else
  6525. callback(buffer);
  6526. }
  6527. else {
  6528. var onload = function (img) {
  6529. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6530. var isPot = (img.width === potWidth && img.height === potHeight);
  6531. if (!isPot) {
  6532. _this._prepareWorkingCanvas();
  6533. _this._workingCanvas.width = potWidth;
  6534. _this._workingCanvas.height = potHeight;
  6535. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6536. _this._workingContext.imageSmoothingEnabled = false;
  6537. _this._workingContext.mozImageSmoothingEnabled = false;
  6538. _this._workingContext.oImageSmoothingEnabled = false;
  6539. _this._workingContext.webkitImageSmoothingEnabled = false;
  6540. _this._workingContext.msImageSmoothingEnabled = false;
  6541. }
  6542. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6543. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6544. _this._workingContext.imageSmoothingEnabled = true;
  6545. _this._workingContext.mozImageSmoothingEnabled = true;
  6546. _this._workingContext.oImageSmoothingEnabled = true;
  6547. _this._workingContext.webkitImageSmoothingEnabled = true;
  6548. _this._workingContext.msImageSmoothingEnabled = true;
  6549. }
  6550. }
  6551. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6552. }, onLoad, samplingMode);
  6553. };
  6554. if (!(fromData instanceof Array))
  6555. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6556. else
  6557. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6558. }
  6559. return texture;
  6560. };
  6561. Engine.prototype._getInternalFormat = function (format) {
  6562. var internalFormat = this._gl.RGBA;
  6563. switch (format) {
  6564. case Engine.TEXTUREFORMAT_ALPHA:
  6565. internalFormat = this._gl.ALPHA;
  6566. break;
  6567. case Engine.TEXTUREFORMAT_LUMINANCE:
  6568. internalFormat = this._gl.LUMINANCE;
  6569. break;
  6570. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6571. internalFormat = this._gl.LUMINANCE_ALPHA;
  6572. break;
  6573. case Engine.TEXTUREFORMAT_RGB:
  6574. internalFormat = this._gl.RGB;
  6575. break;
  6576. case Engine.TEXTUREFORMAT_RGBA:
  6577. internalFormat = this._gl.RGBA;
  6578. break;
  6579. }
  6580. return internalFormat;
  6581. };
  6582. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6583. if (compression === void 0) { compression = null; }
  6584. var internalFormat = this._getInternalFormat(format);
  6585. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6586. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6587. if (compression) {
  6588. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6589. }
  6590. else {
  6591. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6592. }
  6593. if (texture.generateMipMaps) {
  6594. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6595. }
  6596. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6597. this.resetTextureCache();
  6598. texture.isReady = true;
  6599. };
  6600. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6601. if (compression === void 0) { compression = null; }
  6602. var texture = this._gl.createTexture();
  6603. texture._baseWidth = width;
  6604. texture._baseHeight = height;
  6605. texture._width = width;
  6606. texture._height = height;
  6607. texture.references = 1;
  6608. this.updateRawTexture(texture, data, format, invertY, compression);
  6609. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6610. // Filters
  6611. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6612. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6613. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6614. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6615. texture.samplingMode = samplingMode;
  6616. this._loadedTexturesCache.push(texture);
  6617. return texture;
  6618. };
  6619. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6620. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6621. var texture = this._gl.createTexture();
  6622. texture._baseWidth = width;
  6623. texture._baseHeight = height;
  6624. if (forceExponantOfTwo) {
  6625. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6626. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6627. }
  6628. this.resetTextureCache();
  6629. texture._width = width;
  6630. texture._height = height;
  6631. texture.isReady = false;
  6632. texture.generateMipMaps = generateMipMaps;
  6633. texture.references = 1;
  6634. texture.samplingMode = samplingMode;
  6635. this.updateTextureSamplingMode(samplingMode, texture);
  6636. this._loadedTexturesCache.push(texture);
  6637. return texture;
  6638. };
  6639. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6640. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6641. if (texture.isCube) {
  6642. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6643. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6644. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6645. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6646. }
  6647. else {
  6648. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  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. }
  6653. };
  6654. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6655. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6656. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6657. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6658. if (texture.generateMipMaps) {
  6659. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6660. }
  6661. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6662. this.resetTextureCache();
  6663. texture.isReady = true;
  6664. };
  6665. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6666. if (texture._isDisabled) {
  6667. return;
  6668. }
  6669. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6670. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6671. try {
  6672. // Testing video texture support
  6673. if (this._videoTextureSupported === undefined) {
  6674. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6675. if (this._gl.getError() !== 0) {
  6676. this._videoTextureSupported = false;
  6677. }
  6678. else {
  6679. this._videoTextureSupported = true;
  6680. }
  6681. }
  6682. // Copy video through the current working canvas if video texture is not supported
  6683. if (!this._videoTextureSupported) {
  6684. if (!texture._workingCanvas) {
  6685. texture._workingCanvas = document.createElement("canvas");
  6686. texture._workingContext = texture._workingCanvas.getContext("2d");
  6687. texture._workingCanvas.width = texture._width;
  6688. texture._workingCanvas.height = texture._height;
  6689. }
  6690. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6691. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6692. }
  6693. else {
  6694. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6695. }
  6696. if (texture.generateMipMaps) {
  6697. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6698. }
  6699. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6700. this.resetTextureCache();
  6701. texture.isReady = true;
  6702. }
  6703. catch (ex) {
  6704. // Something unexpected
  6705. // Let's disable the texture
  6706. texture._isDisabled = true;
  6707. }
  6708. };
  6709. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6710. // old version had a "generateMipMaps" arg instead of options.
  6711. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6712. // in the same way, generateDepthBuffer is defaulted to true
  6713. var generateMipMaps = false;
  6714. var generateDepthBuffer = true;
  6715. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6716. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6717. if (options !== undefined) {
  6718. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6719. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6720. type = options.type === undefined ? type : options.type;
  6721. if (options.samplingMode !== undefined) {
  6722. samplingMode = options.samplingMode;
  6723. }
  6724. if (type === Engine.TEXTURETYPE_FLOAT) {
  6725. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6726. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6727. }
  6728. }
  6729. var gl = this._gl;
  6730. var texture = gl.createTexture();
  6731. gl.bindTexture(gl.TEXTURE_2D, texture);
  6732. var width = size.width || size;
  6733. var height = size.height || size;
  6734. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6735. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6736. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6737. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6738. }
  6739. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6740. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6741. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6743. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6744. var depthBuffer;
  6745. // Create the depth buffer
  6746. if (generateDepthBuffer) {
  6747. depthBuffer = gl.createRenderbuffer();
  6748. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6749. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6750. }
  6751. // Create the framebuffer
  6752. var framebuffer = gl.createFramebuffer();
  6753. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6754. if (generateDepthBuffer) {
  6755. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6756. }
  6757. if (generateMipMaps) {
  6758. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6759. }
  6760. // Unbind
  6761. gl.bindTexture(gl.TEXTURE_2D, null);
  6762. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6763. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6764. texture._framebuffer = framebuffer;
  6765. if (generateDepthBuffer) {
  6766. texture._depthBuffer = depthBuffer;
  6767. }
  6768. texture._width = width;
  6769. texture._height = height;
  6770. texture.isReady = true;
  6771. texture.generateMipMaps = generateMipMaps;
  6772. texture.references = 1;
  6773. texture.samplingMode = samplingMode;
  6774. this.resetTextureCache();
  6775. this._loadedTexturesCache.push(texture);
  6776. return texture;
  6777. };
  6778. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6779. var gl = this._gl;
  6780. var texture = gl.createTexture();
  6781. var generateMipMaps = true;
  6782. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6783. if (options !== undefined) {
  6784. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6785. if (options.samplingMode !== undefined) {
  6786. samplingMode = options.samplingMode;
  6787. }
  6788. }
  6789. texture.isCube = true;
  6790. texture.references = 1;
  6791. texture.generateMipMaps = generateMipMaps;
  6792. texture.references = 1;
  6793. texture.samplingMode = samplingMode;
  6794. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6795. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6796. for (var face = 0; face < 6; face++) {
  6797. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6798. }
  6799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6803. // Create the depth buffer
  6804. var depthBuffer = gl.createRenderbuffer();
  6805. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6806. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6807. // Create the framebuffer
  6808. var framebuffer = gl.createFramebuffer();
  6809. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6810. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6811. // Mipmaps
  6812. if (texture.generateMipMaps) {
  6813. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6814. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6815. }
  6816. // Unbind
  6817. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6818. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6819. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6820. texture._framebuffer = framebuffer;
  6821. texture._depthBuffer = depthBuffer;
  6822. this.resetTextureCache();
  6823. texture._width = size;
  6824. texture._height = size;
  6825. texture.isReady = true;
  6826. return texture;
  6827. };
  6828. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6829. var _this = this;
  6830. var gl = this._gl;
  6831. var texture = gl.createTexture();
  6832. texture.isCube = true;
  6833. texture.url = rootUrl;
  6834. texture.references = 1;
  6835. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6836. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6837. if (isDDS) {
  6838. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6839. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6840. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6841. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6842. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6843. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6844. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6845. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6846. }
  6847. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6851. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6852. _this.resetTextureCache();
  6853. texture._width = info.width;
  6854. texture._height = info.height;
  6855. texture.isReady = true;
  6856. }, null, null, true);
  6857. }
  6858. else {
  6859. cascadeLoad(rootUrl, scene, function (imgs) {
  6860. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6861. var height = width;
  6862. _this._prepareWorkingCanvas();
  6863. _this._workingCanvas.width = width;
  6864. _this._workingCanvas.height = height;
  6865. var faces = [
  6866. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6867. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6868. ];
  6869. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6870. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6871. for (var index = 0; index < faces.length; index++) {
  6872. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6873. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6874. }
  6875. if (!noMipmap) {
  6876. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6877. }
  6878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6882. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6883. _this.resetTextureCache();
  6884. texture._width = width;
  6885. texture._height = height;
  6886. texture.isReady = true;
  6887. }, files);
  6888. }
  6889. return texture;
  6890. };
  6891. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6892. var _this = this;
  6893. var gl = this._gl;
  6894. var texture = gl.createTexture();
  6895. scene._addPendingData(texture);
  6896. texture.isCube = true;
  6897. texture.references = 1;
  6898. texture.url = url;
  6899. var internalFormat = this._getInternalFormat(format);
  6900. var textureType = gl.UNSIGNED_BYTE;
  6901. if (type === Engine.TEXTURETYPE_FLOAT) {
  6902. textureType = gl.FLOAT;
  6903. }
  6904. var width = size;
  6905. var height = width;
  6906. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6907. texture._width = width;
  6908. texture._height = height;
  6909. var onerror = function () {
  6910. scene._removePendingData(texture);
  6911. };
  6912. var internalCallback = function (data) {
  6913. var rgbeDataArrays = callback(data);
  6914. var facesIndex = [
  6915. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6916. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6917. ];
  6918. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6919. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6920. if (!noMipmap && isPot) {
  6921. if (mipmmapGenerator) {
  6922. var arrayTemp = [];
  6923. // Data are known to be in +X +Y +Z -X -Y -Z
  6924. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6925. arrayTemp.push(rgbeDataArrays[0]); // +X
  6926. arrayTemp.push(rgbeDataArrays[3]); // -X
  6927. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6928. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6929. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6930. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6931. var mipData = mipmmapGenerator(arrayTemp);
  6932. for (var level = 0; level < mipData.length; level++) {
  6933. var mipSize = width >> level;
  6934. // mipData is order in +X -X +Y -Y +Z -Z
  6935. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6936. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6937. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6938. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6939. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6940. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6941. }
  6942. }
  6943. else {
  6944. // Data are known to be in +X +Y +Z -X -Y -Z
  6945. for (var index = 0; index < facesIndex.length; index++) {
  6946. var faceData = rgbeDataArrays[index];
  6947. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6948. }
  6949. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6950. }
  6951. }
  6952. else {
  6953. noMipmap = true;
  6954. }
  6955. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6957. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6958. }
  6959. else {
  6960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6962. }
  6963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6965. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6966. texture.isReady = true;
  6967. _this.resetTextureCache();
  6968. scene._removePendingData(texture);
  6969. };
  6970. BABYLON.Tools.LoadFile(url, function (data) {
  6971. internalCallback(data);
  6972. }, onerror, scene.database, true);
  6973. return texture;
  6974. };
  6975. ;
  6976. Engine.prototype._releaseTexture = function (texture) {
  6977. var gl = this._gl;
  6978. if (texture._framebuffer) {
  6979. gl.deleteFramebuffer(texture._framebuffer);
  6980. }
  6981. if (texture._depthBuffer) {
  6982. gl.deleteRenderbuffer(texture._depthBuffer);
  6983. }
  6984. gl.deleteTexture(texture);
  6985. // Unbind channels
  6986. this.unbindAllTextures();
  6987. var index = this._loadedTexturesCache.indexOf(texture);
  6988. if (index !== -1) {
  6989. this._loadedTexturesCache.splice(index, 1);
  6990. }
  6991. };
  6992. Engine.prototype.bindSamplers = function (effect) {
  6993. this._gl.useProgram(effect.getProgram());
  6994. var samplers = effect.getSamplers();
  6995. for (var index = 0; index < samplers.length; index++) {
  6996. var uniform = effect.getUniform(samplers[index]);
  6997. this._gl.uniform1i(uniform, index);
  6998. }
  6999. this._currentEffect = null;
  7000. };
  7001. Engine.prototype._bindTexture = function (channel, texture) {
  7002. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7003. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7004. this._activeTexturesCache[channel] = null;
  7005. };
  7006. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7007. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7008. };
  7009. Engine.prototype.unbindAllTextures = function () {
  7010. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7011. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7012. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7013. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7014. this._activeTexturesCache[channel] = null;
  7015. }
  7016. };
  7017. Engine.prototype.setTexture = function (channel, texture) {
  7018. if (channel < 0) {
  7019. return;
  7020. }
  7021. // Not ready?
  7022. if (!texture || !texture.isReady()) {
  7023. if (this._activeTexturesCache[channel] != null) {
  7024. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7025. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7026. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7027. this._activeTexturesCache[channel] = null;
  7028. }
  7029. return;
  7030. }
  7031. // Video
  7032. var alreadyActivated = false;
  7033. if (texture instanceof BABYLON.VideoTexture) {
  7034. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7035. alreadyActivated = true;
  7036. texture.update();
  7037. }
  7038. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7039. texture.delayLoad();
  7040. return;
  7041. }
  7042. if (this._activeTexturesCache[channel] === texture) {
  7043. return;
  7044. }
  7045. this._activeTexturesCache[channel] = texture;
  7046. var internalTexture = texture.getInternalTexture();
  7047. if (!alreadyActivated) {
  7048. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7049. }
  7050. if (internalTexture.isCube) {
  7051. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7052. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7053. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7054. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7055. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7056. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7057. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7058. }
  7059. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7060. }
  7061. else {
  7062. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7063. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7064. internalTexture._cachedWrapU = texture.wrapU;
  7065. switch (texture.wrapU) {
  7066. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7067. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7068. break;
  7069. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7070. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7071. break;
  7072. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7073. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7074. break;
  7075. }
  7076. }
  7077. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7078. internalTexture._cachedWrapV = texture.wrapV;
  7079. switch (texture.wrapV) {
  7080. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7081. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7082. break;
  7083. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7084. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7085. break;
  7086. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7087. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7088. break;
  7089. }
  7090. }
  7091. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7092. }
  7093. };
  7094. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7095. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7096. var value = texture.anisotropicFilteringLevel;
  7097. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7098. value = 1;
  7099. }
  7100. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7101. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7102. texture._cachedAnisotropicFilteringLevel = value;
  7103. }
  7104. };
  7105. Engine.prototype.readPixels = function (x, y, width, height) {
  7106. var data = new Uint8Array(height * width * 4);
  7107. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7108. return data;
  7109. };
  7110. Engine.prototype.releaseInternalTexture = function (texture) {
  7111. if (!texture) {
  7112. return;
  7113. }
  7114. texture.references--;
  7115. // Final reference ?
  7116. if (texture.references === 0) {
  7117. var texturesCache = this.getLoadedTexturesCache();
  7118. var index = texturesCache.indexOf(texture);
  7119. if (index > -1) {
  7120. texturesCache.splice(index, 1);
  7121. }
  7122. this._releaseTexture(texture);
  7123. }
  7124. };
  7125. // Dispose
  7126. Engine.prototype.dispose = function () {
  7127. this.hideLoadingUI();
  7128. this.stopRenderLoop();
  7129. // Release scenes
  7130. while (this.scenes.length) {
  7131. this.scenes[0].dispose();
  7132. }
  7133. // Release audio engine
  7134. Engine.audioEngine.dispose();
  7135. // Release effects
  7136. for (var name in this._compiledEffects) {
  7137. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7138. }
  7139. // Unbind
  7140. for (var i in this._vertexAttribArrays) {
  7141. //making sure this is a string
  7142. var iAsNumber = +i;
  7143. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7144. continue;
  7145. }
  7146. this._gl.disableVertexAttribArray(iAsNumber);
  7147. }
  7148. this._gl = null;
  7149. // Events
  7150. window.removeEventListener("blur", this._onBlur);
  7151. window.removeEventListener("focus", this._onFocus);
  7152. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7153. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7154. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7155. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7156. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7157. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7158. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7159. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7160. };
  7161. // Loading screen
  7162. Engine.prototype.displayLoadingUI = function () {
  7163. this._loadingScreen.displayLoadingUI();
  7164. };
  7165. Engine.prototype.hideLoadingUI = function () {
  7166. this._loadingScreen.hideLoadingUI();
  7167. };
  7168. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7169. get: function () {
  7170. return this._loadingScreen;
  7171. },
  7172. set: function (loadingScreen) {
  7173. this._loadingScreen = loadingScreen;
  7174. },
  7175. enumerable: true,
  7176. configurable: true
  7177. });
  7178. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7179. set: function (text) {
  7180. this._loadingScreen.loadingUIText = text;
  7181. },
  7182. enumerable: true,
  7183. configurable: true
  7184. });
  7185. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7186. set: function (color) {
  7187. this._loadingScreen.loadingUIBackgroundColor = color;
  7188. },
  7189. enumerable: true,
  7190. configurable: true
  7191. });
  7192. // FPS
  7193. Engine.prototype.getFps = function () {
  7194. return this.fps;
  7195. };
  7196. Engine.prototype.getDeltaTime = function () {
  7197. return this.deltaTime;
  7198. };
  7199. Engine.prototype._measureFps = function () {
  7200. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7201. var length = this.previousFramesDuration.length;
  7202. if (length >= 2) {
  7203. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7204. }
  7205. if (length >= this.fpsRange) {
  7206. if (length > this.fpsRange) {
  7207. this.previousFramesDuration.splice(0, 1);
  7208. length = this.previousFramesDuration.length;
  7209. }
  7210. var sum = 0;
  7211. for (var id = 0; id < length - 1; id++) {
  7212. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7213. }
  7214. this.fps = 1000.0 / (sum / (length - 1));
  7215. }
  7216. };
  7217. // Statics
  7218. Engine.isSupported = function () {
  7219. try {
  7220. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7221. if (navigator.isCocoonJS) {
  7222. return true;
  7223. }
  7224. var tempcanvas = document.createElement("canvas");
  7225. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7226. return gl != null && !!window.WebGLRenderingContext;
  7227. }
  7228. catch (e) {
  7229. return false;
  7230. }
  7231. };
  7232. // Const statics
  7233. Engine._ALPHA_DISABLE = 0;
  7234. Engine._ALPHA_ADD = 1;
  7235. Engine._ALPHA_COMBINE = 2;
  7236. Engine._ALPHA_SUBTRACT = 3;
  7237. Engine._ALPHA_MULTIPLY = 4;
  7238. Engine._ALPHA_MAXIMIZED = 5;
  7239. Engine._ALPHA_ONEONE = 6;
  7240. Engine._DELAYLOADSTATE_NONE = 0;
  7241. Engine._DELAYLOADSTATE_LOADED = 1;
  7242. Engine._DELAYLOADSTATE_LOADING = 2;
  7243. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7244. Engine._TEXTUREFORMAT_ALPHA = 0;
  7245. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7246. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7247. Engine._TEXTUREFORMAT_RGB = 4;
  7248. Engine._TEXTUREFORMAT_RGBA = 5;
  7249. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7250. Engine._TEXTURETYPE_FLOAT = 1;
  7251. // Updatable statics so stick with vars here
  7252. Engine.Epsilon = 0.001;
  7253. Engine.CollisionsEpsilon = 0.001;
  7254. Engine.CodeRepository = "src/";
  7255. Engine.ShadersRepository = "src/Shaders/";
  7256. return Engine;
  7257. })();
  7258. BABYLON.Engine = Engine;
  7259. })(BABYLON || (BABYLON = {}));
  7260. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7261. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7262. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7263. 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;
  7264. return c > 3 && r && Object.defineProperty(target, key, r), r;
  7265. };
  7266. var BABYLON;
  7267. (function (BABYLON) {
  7268. /**
  7269. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7270. */
  7271. var Node = (function () {
  7272. /**
  7273. * @constructor
  7274. * @param {string} name - the name and id to be given to this node
  7275. * @param {BABYLON.Scene} the scene this node will be added to
  7276. */
  7277. function Node(name, scene) {
  7278. this.state = "";
  7279. this.animations = new Array();
  7280. this._ranges = {};
  7281. this._childrenFlag = -1;
  7282. this._isEnabled = true;
  7283. this._isReady = true;
  7284. this._currentRenderId = -1;
  7285. this._parentRenderId = -1;
  7286. this.name = name;
  7287. this.id = name;
  7288. this._scene = scene;
  7289. this._initCache();
  7290. }
  7291. Node.prototype.getScene = function () {
  7292. return this._scene;
  7293. };
  7294. Node.prototype.getEngine = function () {
  7295. return this._scene.getEngine();
  7296. };
  7297. // override it in derived class
  7298. Node.prototype.getWorldMatrix = function () {
  7299. return BABYLON.Matrix.Identity();
  7300. };
  7301. // override it in derived class if you add new variables to the cache
  7302. // and call the parent class method
  7303. Node.prototype._initCache = function () {
  7304. this._cache = {};
  7305. this._cache.parent = undefined;
  7306. };
  7307. Node.prototype.updateCache = function (force) {
  7308. if (!force && this.isSynchronized())
  7309. return;
  7310. this._cache.parent = this.parent;
  7311. this._updateCache();
  7312. };
  7313. // override it in derived class if you add new variables to the cache
  7314. // and call the parent class method if !ignoreParentClass
  7315. Node.prototype._updateCache = function (ignoreParentClass) {
  7316. };
  7317. // override it in derived class if you add new variables to the cache
  7318. Node.prototype._isSynchronized = function () {
  7319. return true;
  7320. };
  7321. Node.prototype._markSyncedWithParent = function () {
  7322. this._parentRenderId = this.parent._currentRenderId;
  7323. };
  7324. Node.prototype.isSynchronizedWithParent = function () {
  7325. if (!this.parent) {
  7326. return true;
  7327. }
  7328. if (this._parentRenderId !== this.parent._currentRenderId) {
  7329. return false;
  7330. }
  7331. return this.parent.isSynchronized();
  7332. };
  7333. Node.prototype.isSynchronized = function (updateCache) {
  7334. var check = this.hasNewParent();
  7335. check = check || !this.isSynchronizedWithParent();
  7336. check = check || !this._isSynchronized();
  7337. if (updateCache)
  7338. this.updateCache(true);
  7339. return !check;
  7340. };
  7341. Node.prototype.hasNewParent = function (update) {
  7342. if (this._cache.parent === this.parent)
  7343. return false;
  7344. if (update)
  7345. this._cache.parent = this.parent;
  7346. return true;
  7347. };
  7348. /**
  7349. * Is this node ready to be used/rendered
  7350. * @return {boolean} is it ready
  7351. */
  7352. Node.prototype.isReady = function () {
  7353. return this._isReady;
  7354. };
  7355. /**
  7356. * Is this node enabled.
  7357. * If the node has a parent and is enabled, the parent will be inspected as well.
  7358. * @return {boolean} whether this node (and its parent) is enabled.
  7359. * @see setEnabled
  7360. */
  7361. Node.prototype.isEnabled = function () {
  7362. if (!this._isEnabled) {
  7363. return false;
  7364. }
  7365. if (this.parent) {
  7366. return this.parent.isEnabled();
  7367. }
  7368. return true;
  7369. };
  7370. /**
  7371. * Set the enabled state of this node.
  7372. * @param {boolean} value - the new enabled state
  7373. * @see isEnabled
  7374. */
  7375. Node.prototype.setEnabled = function (value) {
  7376. this._isEnabled = value;
  7377. };
  7378. /**
  7379. * Is this node a descendant of the given node.
  7380. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7381. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7382. * @see parent
  7383. */
  7384. Node.prototype.isDescendantOf = function (ancestor) {
  7385. if (this.parent) {
  7386. if (this.parent === ancestor) {
  7387. return true;
  7388. }
  7389. return this.parent.isDescendantOf(ancestor);
  7390. }
  7391. return false;
  7392. };
  7393. Node.prototype._getDescendants = function (list, results, directDecendantsOnly) {
  7394. if (directDecendantsOnly === void 0) { directDecendantsOnly = false; }
  7395. for (var index = 0; index < list.length; index++) {
  7396. var item = list[index];
  7397. if ((directDecendantsOnly && item.parent === this) || (!directDecendantsOnly && item.isDescendantOf(this))) {
  7398. results.push(item);
  7399. }
  7400. }
  7401. };
  7402. /**
  7403. * Will return all nodes that have this node as parent.
  7404. * @return {BABYLON.Node[]} all children nodes of all types.
  7405. */
  7406. Node.prototype.getDescendants = function (directDecendantsOnly) {
  7407. var results = [];
  7408. this._getDescendants(this._scene.meshes, results, directDecendantsOnly);
  7409. this._getDescendants(this._scene.lights, results, directDecendantsOnly);
  7410. this._getDescendants(this._scene.cameras, results, directDecendantsOnly);
  7411. return results;
  7412. };
  7413. /**
  7414. * @Deprecated, legacy support.
  7415. * use getDecendants instead.
  7416. */
  7417. Node.prototype.getChildren = function () {
  7418. return this.getDescendants(true);
  7419. };
  7420. /**
  7421. * Get all child-meshes of this node.
  7422. */
  7423. Node.prototype.getChildMeshes = function (directDecendantsOnly) {
  7424. var results = [];
  7425. this._getDescendants(this._scene.meshes, results, false);
  7426. return results;
  7427. };
  7428. Node.prototype._setReady = function (state) {
  7429. if (state === this._isReady) {
  7430. return;
  7431. }
  7432. if (!state) {
  7433. this._isReady = false;
  7434. return;
  7435. }
  7436. this._isReady = true;
  7437. if (this.onReady) {
  7438. this.onReady(this);
  7439. }
  7440. };
  7441. Node.prototype.getAnimationByName = function (name) {
  7442. for (var i = 0; i < this.animations.length; i++) {
  7443. var animation = this.animations[i];
  7444. if (animation.name === name) {
  7445. return animation;
  7446. }
  7447. }
  7448. return null;
  7449. };
  7450. Node.prototype.createAnimationRange = function (name, from, to) {
  7451. // check name not already in use
  7452. if (!this._ranges[name]) {
  7453. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7454. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7455. if (this.animations[i]) {
  7456. this.animations[i].createRange(name, from, to);
  7457. }
  7458. }
  7459. }
  7460. };
  7461. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7462. if (deleteFrames === void 0) { deleteFrames = true; }
  7463. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7464. if (this.animations[i]) {
  7465. this.animations[i].deleteRange(name, deleteFrames);
  7466. }
  7467. }
  7468. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7469. };
  7470. Node.prototype.getAnimationRange = function (name) {
  7471. return this._ranges[name];
  7472. };
  7473. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7474. var range = this.getAnimationRange(name);
  7475. if (!range) {
  7476. return null;
  7477. }
  7478. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7479. };
  7480. Node.prototype.serializeAnimationRanges = function () {
  7481. var serializationRanges = [];
  7482. for (var name in this._ranges) {
  7483. var range = {};
  7484. range.name = name;
  7485. range.from = this._ranges[name].from;
  7486. range.to = this._ranges[name].to;
  7487. serializationRanges.push(range);
  7488. }
  7489. return serializationRanges;
  7490. };
  7491. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7492. if (parsedNode.ranges) {
  7493. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7494. var data = parsedNode.ranges[index];
  7495. node.createAnimationRange(data.name, data.from, data.to);
  7496. }
  7497. }
  7498. };
  7499. __decorate([
  7500. BABYLON.serialize()
  7501. ], Node.prototype, "name", void 0);
  7502. __decorate([
  7503. BABYLON.serialize()
  7504. ], Node.prototype, "id", void 0);
  7505. __decorate([
  7506. BABYLON.serialize()
  7507. ], Node.prototype, "uniqueId", void 0);
  7508. __decorate([
  7509. BABYLON.serialize()
  7510. ], Node.prototype, "state", void 0);
  7511. return Node;
  7512. })();
  7513. BABYLON.Node = Node;
  7514. })(BABYLON || (BABYLON = {}));
  7515. var BABYLON;
  7516. (function (BABYLON) {
  7517. var FilesInput = (function () {
  7518. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7519. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7520. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7521. this._engine = p_engine;
  7522. this._canvas = p_canvas;
  7523. this._currentScene = p_scene;
  7524. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7525. this._progressCallback = p_progressCallback;
  7526. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7527. this._textureLoadingCallback = p_textureLoadingCallback;
  7528. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7529. }
  7530. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7531. var _this = this;
  7532. if (p_elementToMonitor) {
  7533. this._elementToMonitor = p_elementToMonitor;
  7534. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7535. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7536. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7537. }
  7538. };
  7539. FilesInput.prototype.renderFunction = function () {
  7540. if (this._additionnalRenderLoopLogicCallback) {
  7541. this._additionnalRenderLoopLogicCallback();
  7542. }
  7543. if (this._currentScene) {
  7544. if (this._textureLoadingCallback) {
  7545. var remaining = this._currentScene.getWaitingItemsCount();
  7546. if (remaining > 0) {
  7547. this._textureLoadingCallback(remaining);
  7548. }
  7549. }
  7550. this._currentScene.render();
  7551. }
  7552. };
  7553. FilesInput.prototype.drag = function (e) {
  7554. e.stopPropagation();
  7555. e.preventDefault();
  7556. };
  7557. FilesInput.prototype.drop = function (eventDrop) {
  7558. eventDrop.stopPropagation();
  7559. eventDrop.preventDefault();
  7560. this.loadFiles(eventDrop);
  7561. };
  7562. FilesInput.prototype.loadFiles = function (event) {
  7563. if (this._startingProcessingFilesCallback)
  7564. this._startingProcessingFilesCallback();
  7565. // Handling data transfer via drag'n'drop
  7566. if (event && event.dataTransfer && event.dataTransfer.files) {
  7567. this._filesToLoad = event.dataTransfer.files;
  7568. }
  7569. // Handling files from input files
  7570. if (event && event.target && event.target.files) {
  7571. this._filesToLoad = event.target.files;
  7572. }
  7573. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7574. for (var i = 0; i < this._filesToLoad.length; i++) {
  7575. switch (this._filesToLoad[i].type) {
  7576. case "image/jpeg":
  7577. case "image/png":
  7578. case "image/bmp":
  7579. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7580. break;
  7581. case "image/targa":
  7582. case "image/vnd.ms-dds":
  7583. case "audio/wav":
  7584. case "audio/x-wav":
  7585. case "audio/mp3":
  7586. case "audio/mpeg":
  7587. case "audio/mpeg3":
  7588. case "audio/x-mpeg-3":
  7589. case "audio/ogg":
  7590. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7591. break;
  7592. default:
  7593. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7594. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7595. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7596. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7597. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7598. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7599. this._sceneFileToLoad = this._filesToLoad[i];
  7600. }
  7601. break;
  7602. }
  7603. }
  7604. this.reload();
  7605. }
  7606. };
  7607. FilesInput.prototype.reload = function () {
  7608. var _this = this;
  7609. var that = this;
  7610. // If a ".babylon" file has been provided
  7611. if (this._sceneFileToLoad) {
  7612. if (this._currentScene) {
  7613. if (BABYLON.Tools.errorsCount > 0) {
  7614. BABYLON.Tools.ClearLogCache();
  7615. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7616. }
  7617. this._engine.stopRenderLoop();
  7618. this._currentScene.dispose();
  7619. }
  7620. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7621. that._currentScene = newScene;
  7622. // Wait for textures and shaders to be ready
  7623. that._currentScene.executeWhenReady(function () {
  7624. // Attach camera to canvas inputs
  7625. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7626. that._currentScene.createDefaultCameraOrLight();
  7627. }
  7628. that._currentScene.activeCamera.attachControl(that._canvas);
  7629. if (that._sceneLoadedCallback) {
  7630. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7631. }
  7632. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7633. });
  7634. }, function (progress) {
  7635. if (_this._progressCallback) {
  7636. _this._progressCallback(progress);
  7637. }
  7638. });
  7639. }
  7640. else {
  7641. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7642. }
  7643. };
  7644. FilesInput.FilesTextures = new Array();
  7645. FilesInput.FilesToLoad = new Array();
  7646. return FilesInput;
  7647. })();
  7648. BABYLON.FilesInput = FilesInput;
  7649. })(BABYLON || (BABYLON = {}));
  7650. var BABYLON;
  7651. (function (BABYLON) {
  7652. var IntersectionInfo = (function () {
  7653. function IntersectionInfo(bu, bv, distance) {
  7654. this.bu = bu;
  7655. this.bv = bv;
  7656. this.distance = distance;
  7657. this.faceId = 0;
  7658. this.subMeshId = 0;
  7659. }
  7660. return IntersectionInfo;
  7661. })();
  7662. BABYLON.IntersectionInfo = IntersectionInfo;
  7663. var PickingInfo = (function () {
  7664. function PickingInfo() {
  7665. this.hit = false;
  7666. this.distance = 0;
  7667. this.pickedPoint = null;
  7668. this.pickedMesh = null;
  7669. this.bu = 0;
  7670. this.bv = 0;
  7671. this.faceId = -1;
  7672. this.subMeshId = 0;
  7673. this.pickedSprite = null;
  7674. }
  7675. // Methods
  7676. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7677. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7678. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7679. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7680. return null;
  7681. }
  7682. var indices = this.pickedMesh.getIndices();
  7683. var result;
  7684. if (useVerticesNormals) {
  7685. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7686. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7687. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7688. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7689. normal0 = normal0.scale(this.bu);
  7690. normal1 = normal1.scale(this.bv);
  7691. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7692. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7693. }
  7694. else {
  7695. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7696. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7697. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7698. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7699. var p1p2 = vertex1.subtract(vertex2);
  7700. var p3p2 = vertex3.subtract(vertex2);
  7701. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7702. }
  7703. if (useWorldCoordinates) {
  7704. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7705. }
  7706. return BABYLON.Vector3.Normalize(result);
  7707. };
  7708. PickingInfo.prototype.getTextureCoordinates = function () {
  7709. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7710. return null;
  7711. }
  7712. var indices = this.pickedMesh.getIndices();
  7713. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7714. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7715. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7716. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7717. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7718. uv1 = uv1.scale(this.bu);
  7719. uv2 = uv2.scale(this.bv);
  7720. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7721. };
  7722. return PickingInfo;
  7723. })();
  7724. BABYLON.PickingInfo = PickingInfo;
  7725. })(BABYLON || (BABYLON = {}));
  7726. var BABYLON;
  7727. (function (BABYLON) {
  7728. var BoundingSphere = (function () {
  7729. function BoundingSphere(minimum, maximum) {
  7730. this.minimum = minimum;
  7731. this.maximum = maximum;
  7732. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7733. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7734. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7735. this.radius = distance * 0.5;
  7736. this.centerWorld = BABYLON.Vector3.Zero();
  7737. this._update(BABYLON.Matrix.Identity());
  7738. }
  7739. // Methods
  7740. BoundingSphere.prototype._update = function (world) {
  7741. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7742. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7743. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7744. };
  7745. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7746. for (var i = 0; i < 6; i++) {
  7747. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7748. return false;
  7749. }
  7750. return true;
  7751. };
  7752. BoundingSphere.prototype.intersectsPoint = function (point) {
  7753. var x = this.centerWorld.x - point.x;
  7754. var y = this.centerWorld.y - point.y;
  7755. var z = this.centerWorld.z - point.z;
  7756. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7757. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7758. return false;
  7759. return true;
  7760. };
  7761. // Statics
  7762. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7763. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7764. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7765. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7766. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7767. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7768. return false;
  7769. return true;
  7770. };
  7771. return BoundingSphere;
  7772. })();
  7773. BABYLON.BoundingSphere = BoundingSphere;
  7774. })(BABYLON || (BABYLON = {}));
  7775. var BABYLON;
  7776. (function (BABYLON) {
  7777. var BoundingBox = (function () {
  7778. function BoundingBox(minimum, maximum) {
  7779. this.minimum = minimum;
  7780. this.maximum = maximum;
  7781. this.vectors = new Array();
  7782. this.vectorsWorld = new Array();
  7783. // Bounding vectors
  7784. this.vectors.push(this.minimum.clone());
  7785. this.vectors.push(this.maximum.clone());
  7786. this.vectors.push(this.minimum.clone());
  7787. this.vectors[2].x = this.maximum.x;
  7788. this.vectors.push(this.minimum.clone());
  7789. this.vectors[3].y = this.maximum.y;
  7790. this.vectors.push(this.minimum.clone());
  7791. this.vectors[4].z = this.maximum.z;
  7792. this.vectors.push(this.maximum.clone());
  7793. this.vectors[5].z = this.minimum.z;
  7794. this.vectors.push(this.maximum.clone());
  7795. this.vectors[6].x = this.minimum.x;
  7796. this.vectors.push(this.maximum.clone());
  7797. this.vectors[7].y = this.minimum.y;
  7798. // OBB
  7799. this.center = this.maximum.add(this.minimum).scale(0.5);
  7800. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7801. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7802. // World
  7803. for (var index = 0; index < this.vectors.length; index++) {
  7804. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7805. }
  7806. this.minimumWorld = BABYLON.Vector3.Zero();
  7807. this.maximumWorld = BABYLON.Vector3.Zero();
  7808. this._update(BABYLON.Matrix.Identity());
  7809. }
  7810. // Methods
  7811. BoundingBox.prototype.getWorldMatrix = function () {
  7812. return this._worldMatrix;
  7813. };
  7814. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7815. this._worldMatrix.copyFrom(matrix);
  7816. return this;
  7817. };
  7818. BoundingBox.prototype._update = function (world) {
  7819. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7820. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7821. for (var index = 0; index < this.vectors.length; index++) {
  7822. var v = this.vectorsWorld[index];
  7823. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7824. if (v.x < this.minimumWorld.x)
  7825. this.minimumWorld.x = v.x;
  7826. if (v.y < this.minimumWorld.y)
  7827. this.minimumWorld.y = v.y;
  7828. if (v.z < this.minimumWorld.z)
  7829. this.minimumWorld.z = v.z;
  7830. if (v.x > this.maximumWorld.x)
  7831. this.maximumWorld.x = v.x;
  7832. if (v.y > this.maximumWorld.y)
  7833. this.maximumWorld.y = v.y;
  7834. if (v.z > this.maximumWorld.z)
  7835. this.maximumWorld.z = v.z;
  7836. }
  7837. // OBB
  7838. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7839. this.center.scaleInPlace(0.5);
  7840. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7841. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7842. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7843. this._worldMatrix = world;
  7844. };
  7845. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7846. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7847. };
  7848. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7849. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7850. };
  7851. BoundingBox.prototype.intersectsPoint = function (point) {
  7852. var delta = -BABYLON.Engine.Epsilon;
  7853. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7854. return false;
  7855. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7856. return false;
  7857. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7858. return false;
  7859. return true;
  7860. };
  7861. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7862. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7863. };
  7864. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7865. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7866. return false;
  7867. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7868. return false;
  7869. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7870. return false;
  7871. return true;
  7872. };
  7873. // Statics
  7874. BoundingBox.Intersects = function (box0, box1) {
  7875. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7876. return false;
  7877. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7878. return false;
  7879. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7880. return false;
  7881. return true;
  7882. };
  7883. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7884. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7885. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7886. return (num <= (sphereRadius * sphereRadius));
  7887. };
  7888. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7889. for (var p = 0; p < 6; p++) {
  7890. for (var i = 0; i < 8; i++) {
  7891. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7892. return false;
  7893. }
  7894. }
  7895. }
  7896. return true;
  7897. };
  7898. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7899. for (var p = 0; p < 6; p++) {
  7900. var inCount = 8;
  7901. for (var i = 0; i < 8; i++) {
  7902. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7903. --inCount;
  7904. }
  7905. else {
  7906. break;
  7907. }
  7908. }
  7909. if (inCount === 0)
  7910. return false;
  7911. }
  7912. return true;
  7913. };
  7914. return BoundingBox;
  7915. })();
  7916. BABYLON.BoundingBox = BoundingBox;
  7917. })(BABYLON || (BABYLON = {}));
  7918. var BABYLON;
  7919. (function (BABYLON) {
  7920. var computeBoxExtents = function (axis, box) {
  7921. var p = BABYLON.Vector3.Dot(box.center, axis);
  7922. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7923. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7924. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7925. var r = r0 + r1 + r2;
  7926. return {
  7927. min: p - r,
  7928. max: p + r
  7929. };
  7930. };
  7931. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7932. var axisOverlap = function (axis, box0, box1) {
  7933. var result0 = computeBoxExtents(axis, box0);
  7934. var result1 = computeBoxExtents(axis, box1);
  7935. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7936. };
  7937. var BoundingInfo = (function () {
  7938. function BoundingInfo(minimum, maximum) {
  7939. this.minimum = minimum;
  7940. this.maximum = maximum;
  7941. this._isLocked = false;
  7942. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7943. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7944. }
  7945. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7946. get: function () {
  7947. return this._isLocked;
  7948. },
  7949. set: function (value) {
  7950. this._isLocked = value;
  7951. },
  7952. enumerable: true,
  7953. configurable: true
  7954. });
  7955. // Methods
  7956. BoundingInfo.prototype.update = function (world) {
  7957. if (this._isLocked) {
  7958. return;
  7959. }
  7960. this.boundingBox._update(world);
  7961. this.boundingSphere._update(world);
  7962. };
  7963. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7964. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7965. return false;
  7966. return this.boundingBox.isInFrustum(frustumPlanes);
  7967. };
  7968. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7969. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7970. };
  7971. BoundingInfo.prototype._checkCollision = function (collider) {
  7972. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7973. };
  7974. BoundingInfo.prototype.intersectsPoint = function (point) {
  7975. if (!this.boundingSphere.centerWorld) {
  7976. return false;
  7977. }
  7978. if (!this.boundingSphere.intersectsPoint(point)) {
  7979. return false;
  7980. }
  7981. if (!this.boundingBox.intersectsPoint(point)) {
  7982. return false;
  7983. }
  7984. return true;
  7985. };
  7986. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7987. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7988. return false;
  7989. }
  7990. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7991. return false;
  7992. }
  7993. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7994. return false;
  7995. }
  7996. if (!precise) {
  7997. return true;
  7998. }
  7999. var box0 = this.boundingBox;
  8000. var box1 = boundingInfo.boundingBox;
  8001. if (!axisOverlap(box0.directions[0], box0, box1))
  8002. return false;
  8003. if (!axisOverlap(box0.directions[1], box0, box1))
  8004. return false;
  8005. if (!axisOverlap(box0.directions[2], box0, box1))
  8006. return false;
  8007. if (!axisOverlap(box1.directions[0], box0, box1))
  8008. return false;
  8009. if (!axisOverlap(box1.directions[1], box0, box1))
  8010. return false;
  8011. if (!axisOverlap(box1.directions[2], box0, box1))
  8012. return false;
  8013. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8014. return false;
  8015. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8016. return false;
  8017. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8018. return false;
  8019. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8020. return false;
  8021. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8022. return false;
  8023. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8024. return false;
  8025. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8026. return false;
  8027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8028. return false;
  8029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8030. return false;
  8031. return true;
  8032. };
  8033. return BoundingInfo;
  8034. })();
  8035. BABYLON.BoundingInfo = BoundingInfo;
  8036. })(BABYLON || (BABYLON = {}));
  8037. var BABYLON;
  8038. (function (BABYLON) {
  8039. var AbstractMesh = (function (_super) {
  8040. __extends(AbstractMesh, _super);
  8041. // Constructor
  8042. function AbstractMesh(name, scene) {
  8043. var _this = this;
  8044. _super.call(this, name, scene);
  8045. // Properties
  8046. this.definedFacingForward = true; // orientation for POV movement & rotation
  8047. this.position = new BABYLON.Vector3(0, 0, 0);
  8048. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8049. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8050. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8051. this.visibility = 1.0;
  8052. this.alphaIndex = Number.MAX_VALUE;
  8053. this.infiniteDistance = false;
  8054. this.isVisible = true;
  8055. this.isPickable = true;
  8056. this.showBoundingBox = false;
  8057. this.showSubMeshesBoundingBox = false;
  8058. this.onDispose = null;
  8059. this.isBlocker = false;
  8060. this.renderingGroupId = 0;
  8061. this.receiveShadows = false;
  8062. this.renderOutline = false;
  8063. this.outlineColor = BABYLON.Color3.Red();
  8064. this.outlineWidth = 0.02;
  8065. this.renderOverlay = false;
  8066. this.overlayColor = BABYLON.Color3.Red();
  8067. this.overlayAlpha = 0.5;
  8068. this.hasVertexAlpha = false;
  8069. this.useVertexColors = true;
  8070. this.applyFog = true;
  8071. this.computeBonesUsingShaders = true;
  8072. this.scalingDeterminant = 1;
  8073. this.numBoneInfluencers = 4;
  8074. this.useOctreeForRenderingSelection = true;
  8075. this.useOctreeForPicking = true;
  8076. this.useOctreeForCollisions = true;
  8077. this.layerMask = 0x0FFFFFFF;
  8078. this.alwaysSelectAsActiveMesh = false;
  8079. // Collisions
  8080. this._checkCollisions = false;
  8081. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8082. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8083. this._collider = new BABYLON.Collider();
  8084. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8085. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8086. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8087. // Edges
  8088. this.edgesWidth = 1;
  8089. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8090. // Cache
  8091. this._localWorld = BABYLON.Matrix.Zero();
  8092. this._worldMatrix = BABYLON.Matrix.Zero();
  8093. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8094. this._absolutePosition = BABYLON.Vector3.Zero();
  8095. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8096. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8097. this._isDirty = false;
  8098. this._pivotMatrix = BABYLON.Matrix.Identity();
  8099. this._isDisposed = false;
  8100. this._renderId = 0;
  8101. this._intersectionsInProgress = new Array();
  8102. this._onAfterWorldMatrixUpdate = new Array();
  8103. this._isWorldMatrixFrozen = false;
  8104. this._unIndexed = false;
  8105. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8106. if (collidedMesh === void 0) { collidedMesh = null; }
  8107. //TODO move this to the collision coordinator!
  8108. if (_this.getScene().workerCollisions)
  8109. newPosition.multiplyInPlace(_this._collider.radius);
  8110. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8111. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8112. _this.position.addInPlace(_this._diffPositionForCollisions);
  8113. }
  8114. if (_this.onCollide && collidedMesh) {
  8115. _this.onCollide(collidedMesh);
  8116. }
  8117. if (_this.onCollisionPositionChange) {
  8118. _this.onCollisionPositionChange(_this.position);
  8119. }
  8120. };
  8121. scene.addMesh(this);
  8122. }
  8123. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8124. get: function () {
  8125. return AbstractMesh._BILLBOARDMODE_NONE;
  8126. },
  8127. enumerable: true,
  8128. configurable: true
  8129. });
  8130. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8131. get: function () {
  8132. return AbstractMesh._BILLBOARDMODE_X;
  8133. },
  8134. enumerable: true,
  8135. configurable: true
  8136. });
  8137. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8138. get: function () {
  8139. return AbstractMesh._BILLBOARDMODE_Y;
  8140. },
  8141. enumerable: true,
  8142. configurable: true
  8143. });
  8144. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8145. get: function () {
  8146. return AbstractMesh._BILLBOARDMODE_Z;
  8147. },
  8148. enumerable: true,
  8149. configurable: true
  8150. });
  8151. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8152. get: function () {
  8153. return AbstractMesh._BILLBOARDMODE_ALL;
  8154. },
  8155. enumerable: true,
  8156. configurable: true
  8157. });
  8158. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8159. get: function () {
  8160. return this._skeleton;
  8161. },
  8162. set: function (value) {
  8163. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8164. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8165. }
  8166. if (value && value.needInitialSkinMatrix) {
  8167. value._registerMeshWithPoseMatrix(this);
  8168. }
  8169. this._skeleton = value;
  8170. if (!this._skeleton) {
  8171. this._bonesTransformMatrices = null;
  8172. }
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8178. /**
  8179. * Getting the rotation object.
  8180. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8181. */
  8182. get: function () {
  8183. return this._rotation;
  8184. },
  8185. set: function (newRotation) {
  8186. this._rotation = newRotation;
  8187. },
  8188. enumerable: true,
  8189. configurable: true
  8190. });
  8191. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8192. get: function () {
  8193. return this._scaling;
  8194. },
  8195. set: function (newScaling) {
  8196. this._scaling = newScaling;
  8197. if (this.physicsImpostor) {
  8198. this.physicsImpostor.forceUpdate();
  8199. }
  8200. },
  8201. enumerable: true,
  8202. configurable: true
  8203. });
  8204. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8205. get: function () {
  8206. return this._rotationQuaternion;
  8207. },
  8208. set: function (quaternion) {
  8209. this._rotationQuaternion = quaternion;
  8210. //reset the rotation vector.
  8211. if (this.rotation.length()) {
  8212. this.rotation.copyFromFloats(0, 0, 0);
  8213. }
  8214. },
  8215. enumerable: true,
  8216. configurable: true
  8217. });
  8218. // Methods
  8219. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8220. this._poseMatrix.copyFrom(matrix);
  8221. };
  8222. AbstractMesh.prototype.getPoseMatrix = function () {
  8223. return this._poseMatrix;
  8224. };
  8225. AbstractMesh.prototype.disableEdgesRendering = function () {
  8226. if (this._edgesRenderer !== undefined) {
  8227. this._edgesRenderer.dispose();
  8228. this._edgesRenderer = undefined;
  8229. }
  8230. };
  8231. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8232. if (epsilon === void 0) { epsilon = 0.95; }
  8233. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8234. this.disableEdgesRendering();
  8235. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8236. };
  8237. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8238. get: function () {
  8239. return false;
  8240. },
  8241. enumerable: true,
  8242. configurable: true
  8243. });
  8244. AbstractMesh.prototype.getLOD = function (camera) {
  8245. return this;
  8246. };
  8247. AbstractMesh.prototype.getTotalVertices = function () {
  8248. return 0;
  8249. };
  8250. AbstractMesh.prototype.getIndices = function () {
  8251. return null;
  8252. };
  8253. AbstractMesh.prototype.getVerticesData = function (kind) {
  8254. return null;
  8255. };
  8256. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8257. return false;
  8258. };
  8259. AbstractMesh.prototype.getBoundingInfo = function () {
  8260. if (this._masterMesh) {
  8261. return this._masterMesh.getBoundingInfo();
  8262. }
  8263. if (!this._boundingInfo) {
  8264. this._updateBoundingInfo();
  8265. }
  8266. return this._boundingInfo;
  8267. };
  8268. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8269. get: function () {
  8270. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. AbstractMesh.prototype._preActivate = function () {
  8276. };
  8277. AbstractMesh.prototype._activate = function (renderId) {
  8278. this._renderId = renderId;
  8279. };
  8280. AbstractMesh.prototype.getWorldMatrix = function () {
  8281. if (this._masterMesh) {
  8282. return this._masterMesh.getWorldMatrix();
  8283. }
  8284. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8285. this.computeWorldMatrix();
  8286. }
  8287. return this._worldMatrix;
  8288. };
  8289. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8290. get: function () {
  8291. return this._worldMatrix;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8297. get: function () {
  8298. return this._absolutePosition;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8304. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8305. this.computeWorldMatrix(true);
  8306. this._isWorldMatrixFrozen = true;
  8307. };
  8308. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8309. this._isWorldMatrixFrozen = false;
  8310. this.computeWorldMatrix(true);
  8311. };
  8312. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8313. get: function () {
  8314. return this._isWorldMatrixFrozen;
  8315. },
  8316. enumerable: true,
  8317. configurable: true
  8318. });
  8319. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8320. axis.normalize();
  8321. if (!this.rotationQuaternion) {
  8322. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8323. this.rotation = BABYLON.Vector3.Zero();
  8324. }
  8325. var rotationQuaternion;
  8326. if (!space || space === BABYLON.Space.LOCAL) {
  8327. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8328. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8329. }
  8330. else {
  8331. if (this.parent) {
  8332. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8333. invertParentWorldMatrix.invert();
  8334. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8335. }
  8336. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8337. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8338. }
  8339. };
  8340. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8341. var displacementVector = axis.scale(distance);
  8342. if (!space || space === BABYLON.Space.LOCAL) {
  8343. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8344. this.setPositionWithLocalVector(tempV3);
  8345. }
  8346. else {
  8347. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8348. }
  8349. };
  8350. AbstractMesh.prototype.getAbsolutePosition = function () {
  8351. this.computeWorldMatrix();
  8352. return this._absolutePosition;
  8353. };
  8354. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8355. if (!absolutePosition) {
  8356. return;
  8357. }
  8358. var absolutePositionX;
  8359. var absolutePositionY;
  8360. var absolutePositionZ;
  8361. if (absolutePosition.x === undefined) {
  8362. if (arguments.length < 3) {
  8363. return;
  8364. }
  8365. absolutePositionX = arguments[0];
  8366. absolutePositionY = arguments[1];
  8367. absolutePositionZ = arguments[2];
  8368. }
  8369. else {
  8370. absolutePositionX = absolutePosition.x;
  8371. absolutePositionY = absolutePosition.y;
  8372. absolutePositionZ = absolutePosition.z;
  8373. }
  8374. if (this.parent) {
  8375. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8376. invertParentWorldMatrix.invert();
  8377. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8378. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8379. }
  8380. else {
  8381. this.position.x = absolutePositionX;
  8382. this.position.y = absolutePositionY;
  8383. this.position.z = absolutePositionZ;
  8384. }
  8385. };
  8386. // ================================== Point of View Movement =================================
  8387. /**
  8388. * Perform relative position change from the point of view of behind the front of the mesh.
  8389. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8390. * Supports definition of mesh facing forward or backward.
  8391. * @param {number} amountRight
  8392. * @param {number} amountUp
  8393. * @param {number} amountForward
  8394. */
  8395. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8396. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8397. };
  8398. /**
  8399. * Calculate relative position change from the point of view of behind the front of the mesh.
  8400. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8401. * Supports definition of mesh facing forward or backward.
  8402. * @param {number} amountRight
  8403. * @param {number} amountUp
  8404. * @param {number} amountForward
  8405. */
  8406. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8407. var rotMatrix = new BABYLON.Matrix();
  8408. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8409. rotQuaternion.toRotationMatrix(rotMatrix);
  8410. var translationDelta = BABYLON.Vector3.Zero();
  8411. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8412. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8413. return translationDelta;
  8414. };
  8415. // ================================== Point of View Rotation =================================
  8416. /**
  8417. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8418. * Supports definition of mesh facing forward or backward.
  8419. * @param {number} flipBack
  8420. * @param {number} twirlClockwise
  8421. * @param {number} tiltRight
  8422. */
  8423. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8424. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8425. };
  8426. /**
  8427. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8428. * Supports definition of mesh facing forward or backward.
  8429. * @param {number} flipBack
  8430. * @param {number} twirlClockwise
  8431. * @param {number} tiltRight
  8432. */
  8433. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8434. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8435. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8436. };
  8437. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8438. this._pivotMatrix = matrix;
  8439. this._cache.pivotMatrixUpdated = true;
  8440. };
  8441. AbstractMesh.prototype.getPivotMatrix = function () {
  8442. return this._pivotMatrix;
  8443. };
  8444. AbstractMesh.prototype._isSynchronized = function () {
  8445. if (this._isDirty) {
  8446. return false;
  8447. }
  8448. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8449. return false;
  8450. if (this._cache.pivotMatrixUpdated) {
  8451. return false;
  8452. }
  8453. if (this.infiniteDistance) {
  8454. return false;
  8455. }
  8456. if (!this._cache.position.equals(this.position))
  8457. return false;
  8458. if (this.rotationQuaternion) {
  8459. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8460. return false;
  8461. }
  8462. else {
  8463. if (!this._cache.rotation.equals(this.rotation))
  8464. return false;
  8465. }
  8466. if (!this._cache.scaling.equals(this.scaling))
  8467. return false;
  8468. return true;
  8469. };
  8470. AbstractMesh.prototype._initCache = function () {
  8471. _super.prototype._initCache.call(this);
  8472. this._cache.localMatrixUpdated = false;
  8473. this._cache.position = BABYLON.Vector3.Zero();
  8474. this._cache.scaling = BABYLON.Vector3.Zero();
  8475. this._cache.rotation = BABYLON.Vector3.Zero();
  8476. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8477. this._cache.billboardMode = -1;
  8478. };
  8479. AbstractMesh.prototype.markAsDirty = function (property) {
  8480. if (property === "rotation") {
  8481. this.rotationQuaternion = null;
  8482. }
  8483. this._currentRenderId = Number.MAX_VALUE;
  8484. this._isDirty = true;
  8485. };
  8486. AbstractMesh.prototype._updateBoundingInfo = function () {
  8487. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8488. this._boundingInfo.update(this.worldMatrixFromCache);
  8489. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8490. };
  8491. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8492. if (!this.subMeshes) {
  8493. return;
  8494. }
  8495. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8496. var subMesh = this.subMeshes[subIndex];
  8497. if (!subMesh.IsGlobal) {
  8498. subMesh.updateBoundingInfo(matrix);
  8499. }
  8500. }
  8501. };
  8502. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8503. if (this._isWorldMatrixFrozen) {
  8504. return this._worldMatrix;
  8505. }
  8506. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8507. this._currentRenderId = this.getScene().getRenderId();
  8508. return this._worldMatrix;
  8509. }
  8510. this._cache.position.copyFrom(this.position);
  8511. this._cache.scaling.copyFrom(this.scaling);
  8512. this._cache.pivotMatrixUpdated = false;
  8513. this._cache.billboardMode = this.billboardMode;
  8514. this._currentRenderId = this.getScene().getRenderId();
  8515. this._isDirty = false;
  8516. // Scaling
  8517. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8518. // Rotation
  8519. //rotate, if quaternion is set and rotation was used
  8520. if (this.rotationQuaternion) {
  8521. var len = this.rotation.length();
  8522. if (len) {
  8523. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8524. this.rotation.copyFromFloats(0, 0, 0);
  8525. }
  8526. }
  8527. if (this.rotationQuaternion) {
  8528. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8529. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8530. }
  8531. else {
  8532. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8533. this._cache.rotation.copyFrom(this.rotation);
  8534. }
  8535. // Translation
  8536. if (this.infiniteDistance && !this.parent) {
  8537. var camera = this.getScene().activeCamera;
  8538. if (camera) {
  8539. var cameraWorldMatrix = camera.getWorldMatrix();
  8540. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8541. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8542. }
  8543. }
  8544. else {
  8545. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8546. }
  8547. // Composing transformations
  8548. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8549. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8550. // Billboarding
  8551. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8552. var localPosition = this.position.clone();
  8553. var zero = this.getScene().activeCamera.globalPosition.clone();
  8554. if (this.parent && this.parent.position) {
  8555. localPosition.addInPlace(this.parent.position);
  8556. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8557. }
  8558. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8559. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8560. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8561. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8562. zero.y = localPosition.y + 0.001;
  8563. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8564. zero.z = localPosition.z + 0.001;
  8565. }
  8566. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8567. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8568. BABYLON.Tmp.Matrix[3].invert();
  8569. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8570. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8571. }
  8572. // Local world
  8573. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8574. // Parent
  8575. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8576. this._markSyncedWithParent();
  8577. if (this._meshToBoneReferal) {
  8578. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8579. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8580. }
  8581. else {
  8582. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8583. }
  8584. }
  8585. else {
  8586. this._worldMatrix.copyFrom(this._localWorld);
  8587. }
  8588. // Bounding info
  8589. this._updateBoundingInfo();
  8590. // Absolute position
  8591. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8592. // Callbacks
  8593. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8594. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8595. }
  8596. if (!this._poseMatrix) {
  8597. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8598. }
  8599. return this._worldMatrix;
  8600. };
  8601. /**
  8602. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8603. * @param func: callback function to add
  8604. */
  8605. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8606. this._onAfterWorldMatrixUpdate.push(func);
  8607. };
  8608. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8609. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8610. if (index > -1) {
  8611. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8612. }
  8613. };
  8614. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8615. this.computeWorldMatrix();
  8616. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8617. };
  8618. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8619. this.computeWorldMatrix();
  8620. var invLocalWorldMatrix = this._localWorld.clone();
  8621. invLocalWorldMatrix.invert();
  8622. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8623. };
  8624. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8625. this.computeWorldMatrix(true);
  8626. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8627. };
  8628. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8629. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8630. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8631. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8632. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8633. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8634. /// <returns>Mesh oriented towards targetMesh</returns>
  8635. yawCor = yawCor || 0; // default to zero if undefined
  8636. pitchCor = pitchCor || 0;
  8637. rollCor = rollCor || 0;
  8638. var dv = targetPoint.subtract(this.position);
  8639. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8640. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8641. var pitch = Math.atan2(dv.y, len);
  8642. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8643. };
  8644. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8645. this._meshToBoneReferal = affectedMesh;
  8646. this.parent = bone;
  8647. if (bone.getWorldMatrix().determinant() < 0) {
  8648. this.scalingDeterminant *= -1;
  8649. }
  8650. };
  8651. AbstractMesh.prototype.detachFromBone = function () {
  8652. if (this.parent.getWorldMatrix().determinant() < 0) {
  8653. this.scalingDeterminant *= -1;
  8654. }
  8655. this._meshToBoneReferal = null;
  8656. this.parent = null;
  8657. };
  8658. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8659. return this._boundingInfo.isInFrustum(frustumPlanes);
  8660. };
  8661. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8662. if (!camera) {
  8663. camera = this.getScene().activeCamera;
  8664. }
  8665. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8666. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8667. return false;
  8668. }
  8669. return true;
  8670. };
  8671. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8672. if (!this._boundingInfo || !mesh._boundingInfo) {
  8673. return false;
  8674. }
  8675. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8676. };
  8677. AbstractMesh.prototype.intersectsPoint = function (point) {
  8678. if (!this._boundingInfo) {
  8679. return false;
  8680. }
  8681. return this._boundingInfo.intersectsPoint(point);
  8682. };
  8683. // Physics
  8684. /**
  8685. * @Deprecated. Use new PhysicsImpostor instead.
  8686. * */
  8687. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8688. //legacy support
  8689. if (impostor.impostor) {
  8690. options = impostor;
  8691. impostor = impostor.impostor;
  8692. }
  8693. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options);
  8694. return this.physicsImpostor.physicsBody;
  8695. };
  8696. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8697. return this.physicsImpostor;
  8698. };
  8699. /**
  8700. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8701. */
  8702. AbstractMesh.prototype.getPhysicsMass = function () {
  8703. return this.physicsImpostor.getParam("mass");
  8704. };
  8705. /**
  8706. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8707. */
  8708. AbstractMesh.prototype.getPhysicsFriction = function () {
  8709. return this.physicsImpostor.getParam("friction");
  8710. };
  8711. /**
  8712. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8713. */
  8714. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8715. return this.physicsImpostor.getParam("resitution");
  8716. };
  8717. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8718. if (!camera) {
  8719. camera = this.getScene().activeCamera;
  8720. }
  8721. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8722. };
  8723. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8724. if (!camera) {
  8725. camera = this.getScene().activeCamera;
  8726. }
  8727. return this.absolutePosition.subtract(camera.position).length();
  8728. };
  8729. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8730. if (!this.physicsImpostor) {
  8731. return;
  8732. }
  8733. this.physicsImpostor.applyImpulse(force, contactPoint);
  8734. };
  8735. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8736. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8737. return;
  8738. }
  8739. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8740. mainPivot: pivot1,
  8741. connectedPivot: pivot2,
  8742. nativeParams: options
  8743. });
  8744. };
  8745. /**
  8746. * @Deprecated
  8747. */
  8748. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8749. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8750. this.updatePhysicsBody();
  8751. };
  8752. /**
  8753. * @Deprecated
  8754. * Calling this function is not needed anymore.
  8755. * The physics engine takes care of transofmration automatically.
  8756. */
  8757. AbstractMesh.prototype.updatePhysicsBody = function () {
  8758. //Unneeded
  8759. };
  8760. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8761. // Collisions
  8762. get: function () {
  8763. return this._checkCollisions;
  8764. },
  8765. set: function (collisionEnabled) {
  8766. this._checkCollisions = collisionEnabled;
  8767. if (this.getScene().workerCollisions) {
  8768. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8769. }
  8770. },
  8771. enumerable: true,
  8772. configurable: true
  8773. });
  8774. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8775. var globalPosition = this.getAbsolutePosition();
  8776. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8777. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8778. this._collider.radius = this.ellipsoid;
  8779. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8780. };
  8781. // Submeshes octree
  8782. /**
  8783. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8784. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8785. */
  8786. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8787. if (maxCapacity === void 0) { maxCapacity = 64; }
  8788. if (maxDepth === void 0) { maxDepth = 2; }
  8789. if (!this._submeshesOctree) {
  8790. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8791. }
  8792. this.computeWorldMatrix(true);
  8793. // Update octree
  8794. var bbox = this.getBoundingInfo().boundingBox;
  8795. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8796. return this._submeshesOctree;
  8797. };
  8798. // Collisions
  8799. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8800. this._generatePointsArray();
  8801. // Transformation
  8802. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8803. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8804. subMesh._lastColliderWorldVertices = [];
  8805. subMesh._trianglePlanes = [];
  8806. var start = subMesh.verticesStart;
  8807. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8808. for (var i = start; i < end; i++) {
  8809. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8810. }
  8811. }
  8812. // Collide
  8813. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8814. if (collider.collisionFound) {
  8815. collider.collidedMesh = this;
  8816. }
  8817. };
  8818. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8819. var subMeshes;
  8820. var len;
  8821. // Octrees
  8822. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8823. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8824. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8825. len = intersections.length;
  8826. subMeshes = intersections.data;
  8827. }
  8828. else {
  8829. subMeshes = this.subMeshes;
  8830. len = subMeshes.length;
  8831. }
  8832. for (var index = 0; index < len; index++) {
  8833. var subMesh = subMeshes[index];
  8834. // Bounding test
  8835. if (len > 1 && !subMesh._checkCollision(collider))
  8836. continue;
  8837. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8838. }
  8839. };
  8840. AbstractMesh.prototype._checkCollision = function (collider) {
  8841. // Bounding box test
  8842. if (!this._boundingInfo._checkCollision(collider))
  8843. return;
  8844. // Transformation matrix
  8845. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8846. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8847. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8848. };
  8849. // Picking
  8850. AbstractMesh.prototype._generatePointsArray = function () {
  8851. return false;
  8852. };
  8853. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8854. var pickingInfo = new BABYLON.PickingInfo();
  8855. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8856. return pickingInfo;
  8857. }
  8858. if (!this._generatePointsArray()) {
  8859. return pickingInfo;
  8860. }
  8861. var intersectInfo = null;
  8862. // Octrees
  8863. var subMeshes;
  8864. var len;
  8865. if (this._submeshesOctree && this.useOctreeForPicking) {
  8866. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8867. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8868. len = intersections.length;
  8869. subMeshes = intersections.data;
  8870. }
  8871. else {
  8872. subMeshes = this.subMeshes;
  8873. len = subMeshes.length;
  8874. }
  8875. for (var index = 0; index < len; index++) {
  8876. var subMesh = subMeshes[index];
  8877. // Bounding test
  8878. if (len > 1 && !subMesh.canIntersects(ray))
  8879. continue;
  8880. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8881. if (currentIntersectInfo) {
  8882. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8883. intersectInfo = currentIntersectInfo;
  8884. intersectInfo.subMeshId = index;
  8885. if (fastCheck) {
  8886. break;
  8887. }
  8888. }
  8889. }
  8890. }
  8891. if (intersectInfo) {
  8892. // Get picked point
  8893. var world = this.getWorldMatrix();
  8894. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8895. var direction = ray.direction.clone();
  8896. direction = direction.scale(intersectInfo.distance);
  8897. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8898. var pickedPoint = worldOrigin.add(worldDirection);
  8899. // Return result
  8900. pickingInfo.hit = true;
  8901. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8902. pickingInfo.pickedPoint = pickedPoint;
  8903. pickingInfo.pickedMesh = this;
  8904. pickingInfo.bu = intersectInfo.bu;
  8905. pickingInfo.bv = intersectInfo.bv;
  8906. pickingInfo.faceId = intersectInfo.faceId;
  8907. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8908. return pickingInfo;
  8909. }
  8910. return pickingInfo;
  8911. };
  8912. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8913. return null;
  8914. };
  8915. AbstractMesh.prototype.releaseSubMeshes = function () {
  8916. if (this.subMeshes) {
  8917. while (this.subMeshes.length) {
  8918. this.subMeshes[0].dispose();
  8919. }
  8920. }
  8921. else {
  8922. this.subMeshes = new Array();
  8923. }
  8924. };
  8925. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8926. var index;
  8927. // Action manager
  8928. if (this.actionManager) {
  8929. this.actionManager.dispose();
  8930. this.actionManager = null;
  8931. }
  8932. // Skeleton
  8933. this.skeleton = null;
  8934. // Animations
  8935. this.getScene().stopAnimation(this);
  8936. // Physics
  8937. if (this.physicsImpostor) {
  8938. this.physicsImpostor.dispose(!doNotRecurse);
  8939. }
  8940. // Intersections in progress
  8941. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8942. var other = this._intersectionsInProgress[index];
  8943. var pos = other._intersectionsInProgress.indexOf(this);
  8944. other._intersectionsInProgress.splice(pos, 1);
  8945. }
  8946. this._intersectionsInProgress = [];
  8947. // Edges
  8948. if (this._edgesRenderer) {
  8949. this._edgesRenderer.dispose();
  8950. this._edgesRenderer = null;
  8951. }
  8952. // SubMeshes
  8953. this.releaseSubMeshes();
  8954. // Remove from scene
  8955. this.getScene().removeMesh(this);
  8956. if (!doNotRecurse) {
  8957. // Particles
  8958. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8959. if (this.getScene().particleSystems[index].emitter === this) {
  8960. this.getScene().particleSystems[index].dispose();
  8961. index--;
  8962. }
  8963. }
  8964. // Children
  8965. var objects = this.getScene().meshes.slice(0);
  8966. for (index = 0; index < objects.length; index++) {
  8967. if (objects[index].parent === this) {
  8968. objects[index].dispose();
  8969. }
  8970. }
  8971. }
  8972. else {
  8973. for (index = 0; index < this.getScene().meshes.length; index++) {
  8974. var obj = this.getScene().meshes[index];
  8975. if (obj.parent === this) {
  8976. obj.parent = null;
  8977. obj.computeWorldMatrix(true);
  8978. }
  8979. }
  8980. }
  8981. this._onAfterWorldMatrixUpdate = [];
  8982. this._isDisposed = true;
  8983. // Callback
  8984. if (this.onDispose) {
  8985. this.onDispose();
  8986. }
  8987. };
  8988. // Statics
  8989. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8990. AbstractMesh._BILLBOARDMODE_X = 1;
  8991. AbstractMesh._BILLBOARDMODE_Y = 2;
  8992. AbstractMesh._BILLBOARDMODE_Z = 4;
  8993. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8994. return AbstractMesh;
  8995. })(BABYLON.Node);
  8996. BABYLON.AbstractMesh = AbstractMesh;
  8997. })(BABYLON || (BABYLON = {}));
  8998. var BABYLON;
  8999. (function (BABYLON) {
  9000. var Light = (function (_super) {
  9001. __extends(Light, _super);
  9002. function Light(name, scene) {
  9003. _super.call(this, name, scene);
  9004. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9005. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9006. this.intensity = 1.0;
  9007. this.range = Number.MAX_VALUE;
  9008. this.includeOnlyWithLayerMask = 0;
  9009. this.includedOnlyMeshes = new Array();
  9010. this.excludedMeshes = new Array();
  9011. this.excludeWithLayerMask = 0;
  9012. // PBR Properties.
  9013. this.radius = 0.00001;
  9014. this._excludedMeshesIds = new Array();
  9015. this._includedOnlyMeshesIds = new Array();
  9016. scene.addLight(this);
  9017. }
  9018. Light.prototype.getShadowGenerator = function () {
  9019. return this._shadowGenerator;
  9020. };
  9021. Light.prototype.getAbsolutePosition = function () {
  9022. return BABYLON.Vector3.Zero();
  9023. };
  9024. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9025. };
  9026. Light.prototype._getWorldMatrix = function () {
  9027. return BABYLON.Matrix.Identity();
  9028. };
  9029. Light.prototype.canAffectMesh = function (mesh) {
  9030. if (!mesh) {
  9031. return true;
  9032. }
  9033. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9034. return false;
  9035. }
  9036. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9037. return false;
  9038. }
  9039. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9040. return false;
  9041. }
  9042. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9043. return false;
  9044. }
  9045. return true;
  9046. };
  9047. Light.prototype.getWorldMatrix = function () {
  9048. this._currentRenderId = this.getScene().getRenderId();
  9049. var worldMatrix = this._getWorldMatrix();
  9050. if (this.parent && this.parent.getWorldMatrix) {
  9051. if (!this._parentedWorldMatrix) {
  9052. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9053. }
  9054. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9055. this._markSyncedWithParent();
  9056. return this._parentedWorldMatrix;
  9057. }
  9058. return worldMatrix;
  9059. };
  9060. Light.prototype.dispose = function () {
  9061. if (this._shadowGenerator) {
  9062. this._shadowGenerator.dispose();
  9063. this._shadowGenerator = null;
  9064. }
  9065. // Animations
  9066. this.getScene().stopAnimation(this);
  9067. // Remove from scene
  9068. this.getScene().removeLight(this);
  9069. };
  9070. Light.prototype.getTypeID = function () {
  9071. return 0;
  9072. };
  9073. Light.prototype.clone = function (name) {
  9074. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9075. };
  9076. Light.prototype.serialize = function () {
  9077. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9078. // Type
  9079. serializationObject.type = this.getTypeID();
  9080. // Parent
  9081. if (this.parent) {
  9082. serializationObject.parentId = this.parent.id;
  9083. }
  9084. return serializationObject;
  9085. };
  9086. Light.GetConstructorFromName = function (type, name, scene) {
  9087. switch (type) {
  9088. case 0:
  9089. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9090. case 1:
  9091. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9092. case 2:
  9093. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9094. case 3:
  9095. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9096. }
  9097. };
  9098. Light.Parse = function (parsedLight, scene) {
  9099. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9100. // Inclusion / exclusions
  9101. if (parsedLight.excludedMeshesIds) {
  9102. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9103. }
  9104. if (parsedLight.includedOnlyMeshesIds) {
  9105. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9106. }
  9107. // Parent
  9108. if (parsedLight.parentId) {
  9109. light._waitingParentId = parsedLight.parentId;
  9110. }
  9111. // Animations
  9112. if (parsedLight.animations) {
  9113. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9114. var parsedAnimation = parsedLight.animations[animationIndex];
  9115. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9116. }
  9117. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9118. }
  9119. if (parsedLight.autoAnimate) {
  9120. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  9121. }
  9122. return light;
  9123. };
  9124. __decorate([
  9125. BABYLON.serializeAsColor3()
  9126. ], Light.prototype, "diffuse", void 0);
  9127. __decorate([
  9128. BABYLON.serializeAsColor3()
  9129. ], Light.prototype, "specular", void 0);
  9130. __decorate([
  9131. BABYLON.serialize()
  9132. ], Light.prototype, "intensity", void 0);
  9133. __decorate([
  9134. BABYLON.serialize()
  9135. ], Light.prototype, "range", void 0);
  9136. __decorate([
  9137. BABYLON.serialize()
  9138. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9139. __decorate([
  9140. BABYLON.serialize()
  9141. ], Light.prototype, "radius", void 0);
  9142. return Light;
  9143. })(BABYLON.Node);
  9144. BABYLON.Light = Light;
  9145. })(BABYLON || (BABYLON = {}));
  9146. var BABYLON;
  9147. (function (BABYLON) {
  9148. var PointLight = (function (_super) {
  9149. __extends(PointLight, _super);
  9150. function PointLight(name, position, scene) {
  9151. _super.call(this, name, scene);
  9152. this.position = position;
  9153. }
  9154. PointLight.prototype.getAbsolutePosition = function () {
  9155. return this.transformedPosition ? this.transformedPosition : this.position;
  9156. };
  9157. PointLight.prototype.computeTransformedPosition = function () {
  9158. if (this.parent && this.parent.getWorldMatrix) {
  9159. if (!this.transformedPosition) {
  9160. this.transformedPosition = BABYLON.Vector3.Zero();
  9161. }
  9162. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9163. return true;
  9164. }
  9165. return false;
  9166. };
  9167. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9168. if (this.parent && this.parent.getWorldMatrix) {
  9169. this.computeTransformedPosition();
  9170. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9171. return;
  9172. }
  9173. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9174. };
  9175. PointLight.prototype.needCube = function () {
  9176. return true;
  9177. };
  9178. PointLight.prototype.supportsVSM = function () {
  9179. return false;
  9180. };
  9181. PointLight.prototype.needRefreshPerFrame = function () {
  9182. return false;
  9183. };
  9184. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9185. switch (faceIndex) {
  9186. case 0:
  9187. return new BABYLON.Vector3(1, 0, 0);
  9188. case 1:
  9189. return new BABYLON.Vector3(-1, 0, 0);
  9190. case 2:
  9191. return new BABYLON.Vector3(0, -1, 0);
  9192. case 3:
  9193. return new BABYLON.Vector3(0, 1, 0);
  9194. case 4:
  9195. return new BABYLON.Vector3(0, 0, 1);
  9196. case 5:
  9197. return new BABYLON.Vector3(0, 0, -1);
  9198. }
  9199. return BABYLON.Vector3.Zero();
  9200. };
  9201. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9202. var activeCamera = this.getScene().activeCamera;
  9203. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9204. };
  9205. PointLight.prototype._getWorldMatrix = function () {
  9206. if (!this._worldMatrix) {
  9207. this._worldMatrix = BABYLON.Matrix.Identity();
  9208. }
  9209. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9210. return this._worldMatrix;
  9211. };
  9212. PointLight.prototype.getTypeID = function () {
  9213. return 0;
  9214. };
  9215. __decorate([
  9216. BABYLON.serializeAsVector3()
  9217. ], PointLight.prototype, "position", void 0);
  9218. return PointLight;
  9219. })(BABYLON.Light);
  9220. BABYLON.PointLight = PointLight;
  9221. })(BABYLON || (BABYLON = {}));
  9222. var BABYLON;
  9223. (function (BABYLON) {
  9224. var SpotLight = (function (_super) {
  9225. __extends(SpotLight, _super);
  9226. function SpotLight(name, position, direction, angle, exponent, scene) {
  9227. _super.call(this, name, scene);
  9228. this.position = position;
  9229. this.direction = direction;
  9230. this.angle = angle;
  9231. this.exponent = exponent;
  9232. }
  9233. SpotLight.prototype.getAbsolutePosition = function () {
  9234. return this.transformedPosition ? this.transformedPosition : this.position;
  9235. };
  9236. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9237. var activeCamera = this.getScene().activeCamera;
  9238. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9239. };
  9240. SpotLight.prototype.needCube = function () {
  9241. return false;
  9242. };
  9243. SpotLight.prototype.supportsVSM = function () {
  9244. return true;
  9245. };
  9246. SpotLight.prototype.needRefreshPerFrame = function () {
  9247. return false;
  9248. };
  9249. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9250. return this.direction;
  9251. };
  9252. SpotLight.prototype.setDirectionToTarget = function (target) {
  9253. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9254. return this.direction;
  9255. };
  9256. SpotLight.prototype.computeTransformedPosition = function () {
  9257. if (this.parent && this.parent.getWorldMatrix) {
  9258. if (!this.transformedPosition) {
  9259. this.transformedPosition = BABYLON.Vector3.Zero();
  9260. }
  9261. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9262. return true;
  9263. }
  9264. return false;
  9265. };
  9266. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9267. var normalizeDirection;
  9268. if (this.parent && this.parent.getWorldMatrix) {
  9269. if (!this._transformedDirection) {
  9270. this._transformedDirection = BABYLON.Vector3.Zero();
  9271. }
  9272. this.computeTransformedPosition();
  9273. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9274. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9275. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9276. }
  9277. else {
  9278. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9279. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9280. }
  9281. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9282. };
  9283. SpotLight.prototype._getWorldMatrix = function () {
  9284. if (!this._worldMatrix) {
  9285. this._worldMatrix = BABYLON.Matrix.Identity();
  9286. }
  9287. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9288. return this._worldMatrix;
  9289. };
  9290. SpotLight.prototype.getTypeID = function () {
  9291. return 2;
  9292. };
  9293. __decorate([
  9294. BABYLON.serializeAsVector3()
  9295. ], SpotLight.prototype, "position", void 0);
  9296. __decorate([
  9297. BABYLON.serializeAsVector3()
  9298. ], SpotLight.prototype, "direction", void 0);
  9299. __decorate([
  9300. BABYLON.serialize()
  9301. ], SpotLight.prototype, "angle", void 0);
  9302. __decorate([
  9303. BABYLON.serialize()
  9304. ], SpotLight.prototype, "exponent", void 0);
  9305. return SpotLight;
  9306. })(BABYLON.Light);
  9307. BABYLON.SpotLight = SpotLight;
  9308. })(BABYLON || (BABYLON = {}));
  9309. var BABYLON;
  9310. (function (BABYLON) {
  9311. var HemisphericLight = (function (_super) {
  9312. __extends(HemisphericLight, _super);
  9313. function HemisphericLight(name, direction, scene) {
  9314. _super.call(this, name, scene);
  9315. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9316. this.direction = direction;
  9317. }
  9318. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9319. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9320. return this.direction;
  9321. };
  9322. HemisphericLight.prototype.getShadowGenerator = function () {
  9323. return null;
  9324. };
  9325. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9326. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9327. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9328. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9329. };
  9330. HemisphericLight.prototype._getWorldMatrix = function () {
  9331. if (!this._worldMatrix) {
  9332. this._worldMatrix = BABYLON.Matrix.Identity();
  9333. }
  9334. return this._worldMatrix;
  9335. };
  9336. HemisphericLight.prototype.getTypeID = function () {
  9337. return 3;
  9338. };
  9339. __decorate([
  9340. BABYLON.serializeAsColor3()
  9341. ], HemisphericLight.prototype, "groundColor", void 0);
  9342. __decorate([
  9343. BABYLON.serializeAsVector3()
  9344. ], HemisphericLight.prototype, "direction", void 0);
  9345. return HemisphericLight;
  9346. })(BABYLON.Light);
  9347. BABYLON.HemisphericLight = HemisphericLight;
  9348. })(BABYLON || (BABYLON = {}));
  9349. var BABYLON;
  9350. (function (BABYLON) {
  9351. var DirectionalLight = (function (_super) {
  9352. __extends(DirectionalLight, _super);
  9353. function DirectionalLight(name, direction, scene) {
  9354. _super.call(this, name, scene);
  9355. this.shadowOrthoScale = 0.5;
  9356. this.autoUpdateExtends = true;
  9357. // Cache
  9358. this._orthoLeft = Number.MAX_VALUE;
  9359. this._orthoRight = Number.MIN_VALUE;
  9360. this._orthoTop = Number.MIN_VALUE;
  9361. this._orthoBottom = Number.MAX_VALUE;
  9362. this.position = direction.scale(-1);
  9363. this.direction = direction;
  9364. }
  9365. DirectionalLight.prototype.getAbsolutePosition = function () {
  9366. return this.transformedPosition ? this.transformedPosition : this.position;
  9367. };
  9368. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9369. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9370. return this.direction;
  9371. };
  9372. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9373. var activeCamera = this.getScene().activeCamera;
  9374. // Check extends
  9375. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9376. var tempVector3 = BABYLON.Vector3.Zero();
  9377. this._orthoLeft = Number.MAX_VALUE;
  9378. this._orthoRight = Number.MIN_VALUE;
  9379. this._orthoTop = Number.MIN_VALUE;
  9380. this._orthoBottom = Number.MAX_VALUE;
  9381. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9382. var mesh = renderList[meshIndex];
  9383. if (!mesh) {
  9384. continue;
  9385. }
  9386. var boundingInfo = mesh.getBoundingInfo();
  9387. if (!boundingInfo) {
  9388. continue;
  9389. }
  9390. var boundingBox = boundingInfo.boundingBox;
  9391. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9392. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9393. if (tempVector3.x < this._orthoLeft)
  9394. this._orthoLeft = tempVector3.x;
  9395. if (tempVector3.y < this._orthoBottom)
  9396. this._orthoBottom = tempVector3.y;
  9397. if (tempVector3.x > this._orthoRight)
  9398. this._orthoRight = tempVector3.x;
  9399. if (tempVector3.y > this._orthoTop)
  9400. this._orthoTop = tempVector3.y;
  9401. }
  9402. }
  9403. }
  9404. var xOffset = this._orthoRight - this._orthoLeft;
  9405. var yOffset = this._orthoTop - this._orthoBottom;
  9406. 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);
  9407. };
  9408. DirectionalLight.prototype.supportsVSM = function () {
  9409. return true;
  9410. };
  9411. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9412. return true;
  9413. };
  9414. DirectionalLight.prototype.needCube = function () {
  9415. return false;
  9416. };
  9417. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9418. return this.direction;
  9419. };
  9420. DirectionalLight.prototype.computeTransformedPosition = function () {
  9421. if (this.parent && this.parent.getWorldMatrix) {
  9422. if (!this.transformedPosition) {
  9423. this.transformedPosition = BABYLON.Vector3.Zero();
  9424. }
  9425. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9426. return true;
  9427. }
  9428. return false;
  9429. };
  9430. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9431. if (this.parent && this.parent.getWorldMatrix) {
  9432. if (!this._transformedDirection) {
  9433. this._transformedDirection = BABYLON.Vector3.Zero();
  9434. }
  9435. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9436. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9437. return;
  9438. }
  9439. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9440. };
  9441. DirectionalLight.prototype._getWorldMatrix = function () {
  9442. if (!this._worldMatrix) {
  9443. this._worldMatrix = BABYLON.Matrix.Identity();
  9444. }
  9445. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9446. return this._worldMatrix;
  9447. };
  9448. DirectionalLight.prototype.getTypeID = function () {
  9449. return 1;
  9450. };
  9451. __decorate([
  9452. BABYLON.serializeAsVector3()
  9453. ], DirectionalLight.prototype, "position", void 0);
  9454. __decorate([
  9455. BABYLON.serializeAsVector3()
  9456. ], DirectionalLight.prototype, "direction", void 0);
  9457. __decorate([
  9458. BABYLON.serialize()
  9459. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9460. __decorate([
  9461. BABYLON.serialize()
  9462. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9463. return DirectionalLight;
  9464. })(BABYLON.Light);
  9465. BABYLON.DirectionalLight = DirectionalLight;
  9466. })(BABYLON || (BABYLON = {}));
  9467. var BABYLON;
  9468. (function (BABYLON) {
  9469. var ShadowGenerator = (function () {
  9470. function ShadowGenerator(mapSize, light) {
  9471. var _this = this;
  9472. // Members
  9473. this._filter = ShadowGenerator.FILTER_NONE;
  9474. this.blurScale = 2;
  9475. this._blurBoxOffset = 0;
  9476. this._bias = 0.00005;
  9477. this._lightDirection = BABYLON.Vector3.Zero();
  9478. this.forceBackFacesOnly = false;
  9479. this._darkness = 0;
  9480. this._transparencyShadow = false;
  9481. this._viewMatrix = BABYLON.Matrix.Zero();
  9482. this._projectionMatrix = BABYLON.Matrix.Zero();
  9483. this._transformMatrix = BABYLON.Matrix.Zero();
  9484. this._worldViewProjection = BABYLON.Matrix.Zero();
  9485. this._currentFaceIndex = 0;
  9486. this._currentFaceIndexCache = 0;
  9487. this._light = light;
  9488. this._scene = light.getScene();
  9489. this._mapSize = mapSize;
  9490. light._shadowGenerator = this;
  9491. // Render target
  9492. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9493. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9494. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9495. this._shadowMap.anisotropicFilteringLevel = 1;
  9496. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9497. this._shadowMap.renderParticles = false;
  9498. this._shadowMap.onBeforeRender = function (faceIndex) {
  9499. _this._currentFaceIndex = faceIndex;
  9500. };
  9501. this._shadowMap.onAfterUnbind = function () {
  9502. if (!_this.useBlurVarianceShadowMap) {
  9503. return;
  9504. }
  9505. if (!_this._shadowMap2) {
  9506. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9507. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9508. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9509. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9510. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9511. _this._downSamplePostprocess.onApply = function (effect) {
  9512. effect.setTexture("textureSampler", _this._shadowMap);
  9513. };
  9514. _this.blurBoxOffset = 1;
  9515. }
  9516. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9517. };
  9518. // Custom render function
  9519. var renderSubMesh = function (subMesh) {
  9520. var mesh = subMesh.getRenderingMesh();
  9521. var scene = _this._scene;
  9522. var engine = scene.getEngine();
  9523. // Culling
  9524. engine.setState(subMesh.getMaterial().backFaceCulling);
  9525. // Managing instances
  9526. var batch = mesh._getInstancesRenderList(subMesh._id);
  9527. if (batch.mustReturn) {
  9528. return;
  9529. }
  9530. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9531. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9532. engine.enableEffect(_this._effect);
  9533. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9534. var material = subMesh.getMaterial();
  9535. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9536. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9537. if (_this.getLight().needCube()) {
  9538. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9539. }
  9540. // Alpha test
  9541. if (material && material.needAlphaTesting()) {
  9542. var alphaTexture = material.getAlphaTestTexture();
  9543. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9544. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9545. }
  9546. // Bones
  9547. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9548. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9549. }
  9550. if (_this.forceBackFacesOnly) {
  9551. engine.setState(true, 0, false, true);
  9552. }
  9553. // Draw
  9554. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9555. if (_this.forceBackFacesOnly) {
  9556. engine.setState(true, 0, false, false);
  9557. }
  9558. }
  9559. else {
  9560. // Need to reset refresh rate of the shadowMap
  9561. _this._shadowMap.resetRefreshCounter();
  9562. }
  9563. };
  9564. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9565. var index;
  9566. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9567. renderSubMesh(opaqueSubMeshes.data[index]);
  9568. }
  9569. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9570. renderSubMesh(alphaTestSubMeshes.data[index]);
  9571. }
  9572. if (_this._transparencyShadow) {
  9573. for (index = 0; index < transparentSubMeshes.length; index++) {
  9574. renderSubMesh(transparentSubMeshes.data[index]);
  9575. }
  9576. }
  9577. };
  9578. this._shadowMap.onClear = function (engine) {
  9579. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9580. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9581. }
  9582. else {
  9583. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9584. }
  9585. };
  9586. }
  9587. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9588. // Static
  9589. get: function () {
  9590. return ShadowGenerator._FILTER_NONE;
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9596. get: function () {
  9597. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9603. get: function () {
  9604. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9610. get: function () {
  9611. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9617. get: function () {
  9618. return this._bias;
  9619. },
  9620. set: function (bias) {
  9621. this._bias = bias;
  9622. },
  9623. enumerable: true,
  9624. configurable: true
  9625. });
  9626. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9627. get: function () {
  9628. return this._blurBoxOffset;
  9629. },
  9630. set: function (value) {
  9631. var _this = this;
  9632. if (this._blurBoxOffset === value) {
  9633. return;
  9634. }
  9635. this._blurBoxOffset = value;
  9636. if (this._boxBlurPostprocess) {
  9637. this._boxBlurPostprocess.dispose();
  9638. }
  9639. 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);
  9640. this._boxBlurPostprocess.onApply = function (effect) {
  9641. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9642. };
  9643. },
  9644. enumerable: true,
  9645. configurable: true
  9646. });
  9647. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9648. get: function () {
  9649. return this._filter;
  9650. },
  9651. set: function (value) {
  9652. if (this._filter === value) {
  9653. return;
  9654. }
  9655. this._filter = value;
  9656. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9657. this._shadowMap.anisotropicFilteringLevel = 16;
  9658. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9659. }
  9660. else {
  9661. this._shadowMap.anisotropicFilteringLevel = 1;
  9662. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9663. }
  9664. },
  9665. enumerable: true,
  9666. configurable: true
  9667. });
  9668. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9669. get: function () {
  9670. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9671. },
  9672. set: function (value) {
  9673. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9679. get: function () {
  9680. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9681. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9682. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9683. },
  9684. set: function (value) {
  9685. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9686. },
  9687. enumerable: true,
  9688. configurable: true
  9689. });
  9690. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9691. get: function () {
  9692. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9693. },
  9694. set: function (value) {
  9695. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9701. var defines = [];
  9702. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9703. defines.push("#define VSM");
  9704. }
  9705. if (this.getLight().needCube()) {
  9706. defines.push("#define CUBEMAP");
  9707. }
  9708. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9709. var mesh = subMesh.getMesh();
  9710. var material = subMesh.getMaterial();
  9711. // Alpha test
  9712. if (material && material.needAlphaTesting()) {
  9713. defines.push("#define ALPHATEST");
  9714. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9715. attribs.push(BABYLON.VertexBuffer.UVKind);
  9716. defines.push("#define UV1");
  9717. }
  9718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9719. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9720. defines.push("#define UV2");
  9721. }
  9722. }
  9723. // Bones
  9724. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9725. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9726. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9727. if (mesh.numBoneInfluencers > 4) {
  9728. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9729. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9730. }
  9731. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9732. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9733. }
  9734. else {
  9735. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9736. }
  9737. // Instances
  9738. if (useInstances) {
  9739. defines.push("#define INSTANCES");
  9740. attribs.push("world0");
  9741. attribs.push("world1");
  9742. attribs.push("world2");
  9743. attribs.push("world3");
  9744. }
  9745. // Get correct effect
  9746. var join = defines.join("\n");
  9747. if (this._cachedDefines !== join) {
  9748. this._cachedDefines = join;
  9749. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9750. }
  9751. return this._effect.isReady();
  9752. };
  9753. ShadowGenerator.prototype.getShadowMap = function () {
  9754. return this._shadowMap;
  9755. };
  9756. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9757. if (this._shadowMap2) {
  9758. return this._shadowMap2;
  9759. }
  9760. return this._shadowMap;
  9761. };
  9762. ShadowGenerator.prototype.getLight = function () {
  9763. return this._light;
  9764. };
  9765. // Methods
  9766. ShadowGenerator.prototype.getTransformMatrix = function () {
  9767. var scene = this._scene;
  9768. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9769. return this._transformMatrix;
  9770. }
  9771. this._currentRenderID = scene.getRenderId();
  9772. this._currentFaceIndexCache = this._currentFaceIndex;
  9773. var lightPosition = this._light.position;
  9774. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9775. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9776. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9777. }
  9778. if (this._light.computeTransformedPosition()) {
  9779. lightPosition = this._light.transformedPosition;
  9780. }
  9781. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9782. this._cachedPosition = lightPosition.clone();
  9783. this._cachedDirection = this._lightDirection.clone();
  9784. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9785. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9786. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9787. }
  9788. return this._transformMatrix;
  9789. };
  9790. ShadowGenerator.prototype.getDarkness = function () {
  9791. return this._darkness;
  9792. };
  9793. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9794. if (darkness >= 1.0)
  9795. this._darkness = 1.0;
  9796. else if (darkness <= 0.0)
  9797. this._darkness = 0.0;
  9798. else
  9799. this._darkness = darkness;
  9800. };
  9801. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9802. this._transparencyShadow = hasShadow;
  9803. };
  9804. ShadowGenerator.prototype._packHalf = function (depth) {
  9805. var scale = depth * 255.0;
  9806. var fract = scale - Math.floor(scale);
  9807. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9808. };
  9809. ShadowGenerator.prototype.dispose = function () {
  9810. this._shadowMap.dispose();
  9811. if (this._shadowMap2) {
  9812. this._shadowMap2.dispose();
  9813. }
  9814. if (this._downSamplePostprocess) {
  9815. this._downSamplePostprocess.dispose();
  9816. }
  9817. if (this._boxBlurPostprocess) {
  9818. this._boxBlurPostprocess.dispose();
  9819. }
  9820. };
  9821. ShadowGenerator.prototype.serialize = function () {
  9822. var serializationObject = {};
  9823. serializationObject.lightId = this._light.id;
  9824. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9825. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9826. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9827. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9828. serializationObject.renderList = [];
  9829. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9830. var mesh = this.getShadowMap().renderList[meshIndex];
  9831. serializationObject.renderList.push(mesh.id);
  9832. }
  9833. return serializationObject;
  9834. };
  9835. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9836. //casting to point light, as light is missing the position attr and typescript complains.
  9837. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9838. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9839. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9840. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9841. shadowGenerator.getShadowMap().renderList.push(mesh);
  9842. }
  9843. if (parsedShadowGenerator.usePoissonSampling) {
  9844. shadowGenerator.usePoissonSampling = true;
  9845. }
  9846. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9847. shadowGenerator.useVarianceShadowMap = true;
  9848. }
  9849. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9850. shadowGenerator.useBlurVarianceShadowMap = true;
  9851. if (parsedShadowGenerator.blurScale) {
  9852. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9853. }
  9854. if (parsedShadowGenerator.blurBoxOffset) {
  9855. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9856. }
  9857. }
  9858. if (parsedShadowGenerator.bias !== undefined) {
  9859. shadowGenerator.bias = parsedShadowGenerator.bias;
  9860. }
  9861. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9862. return shadowGenerator;
  9863. };
  9864. ShadowGenerator._FILTER_NONE = 0;
  9865. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9866. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9867. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9868. return ShadowGenerator;
  9869. })();
  9870. BABYLON.ShadowGenerator = ShadowGenerator;
  9871. })(BABYLON || (BABYLON = {}));
  9872. var BABYLON;
  9873. (function (BABYLON) {
  9874. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9875. if (boxMin.x > sphereCenter.x + sphereRadius)
  9876. return false;
  9877. if (sphereCenter.x - sphereRadius > boxMax.x)
  9878. return false;
  9879. if (boxMin.y > sphereCenter.y + sphereRadius)
  9880. return false;
  9881. if (sphereCenter.y - sphereRadius > boxMax.y)
  9882. return false;
  9883. if (boxMin.z > sphereCenter.z + sphereRadius)
  9884. return false;
  9885. if (sphereCenter.z - sphereRadius > boxMax.z)
  9886. return false;
  9887. return true;
  9888. };
  9889. var getLowestRoot = function (a, b, c, maxR) {
  9890. var determinant = b * b - 4.0 * a * c;
  9891. var result = { root: 0, found: false };
  9892. if (determinant < 0)
  9893. return result;
  9894. var sqrtD = Math.sqrt(determinant);
  9895. var r1 = (-b - sqrtD) / (2.0 * a);
  9896. var r2 = (-b + sqrtD) / (2.0 * a);
  9897. if (r1 > r2) {
  9898. var temp = r2;
  9899. r2 = r1;
  9900. r1 = temp;
  9901. }
  9902. if (r1 > 0 && r1 < maxR) {
  9903. result.root = r1;
  9904. result.found = true;
  9905. return result;
  9906. }
  9907. if (r2 > 0 && r2 < maxR) {
  9908. result.root = r2;
  9909. result.found = true;
  9910. return result;
  9911. }
  9912. return result;
  9913. };
  9914. var Collider = (function () {
  9915. function Collider() {
  9916. this.radius = new BABYLON.Vector3(1, 1, 1);
  9917. this.retry = 0;
  9918. this.basePointWorld = BABYLON.Vector3.Zero();
  9919. this.velocityWorld = BABYLON.Vector3.Zero();
  9920. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9921. this._collisionPoint = BABYLON.Vector3.Zero();
  9922. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9923. this._tempVector = BABYLON.Vector3.Zero();
  9924. this._tempVector2 = BABYLON.Vector3.Zero();
  9925. this._tempVector3 = BABYLON.Vector3.Zero();
  9926. this._tempVector4 = BABYLON.Vector3.Zero();
  9927. this._edge = BABYLON.Vector3.Zero();
  9928. this._baseToVertex = BABYLON.Vector3.Zero();
  9929. this._destinationPoint = BABYLON.Vector3.Zero();
  9930. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9931. this._displacementVector = BABYLON.Vector3.Zero();
  9932. }
  9933. // Methods
  9934. Collider.prototype._initialize = function (source, dir, e) {
  9935. this.velocity = dir;
  9936. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9937. this.basePoint = source;
  9938. source.multiplyToRef(this.radius, this.basePointWorld);
  9939. dir.multiplyToRef(this.radius, this.velocityWorld);
  9940. this.velocityWorldLength = this.velocityWorld.length();
  9941. this.epsilon = e;
  9942. this.collisionFound = false;
  9943. };
  9944. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9945. pa.subtractToRef(point, this._tempVector);
  9946. pb.subtractToRef(point, this._tempVector2);
  9947. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9948. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9949. if (d < 0)
  9950. return false;
  9951. pc.subtractToRef(point, this._tempVector3);
  9952. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9953. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9954. if (d < 0)
  9955. return false;
  9956. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9957. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9958. return d >= 0;
  9959. };
  9960. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9961. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9962. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9963. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9964. return false;
  9965. }
  9966. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9967. return false;
  9968. return true;
  9969. };
  9970. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9971. var t0;
  9972. var embeddedInPlane = false;
  9973. //defensive programming, actually not needed.
  9974. if (!trianglePlaneArray) {
  9975. trianglePlaneArray = [];
  9976. }
  9977. if (!trianglePlaneArray[faceIndex]) {
  9978. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9979. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9980. }
  9981. var trianglePlane = trianglePlaneArray[faceIndex];
  9982. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9983. return;
  9984. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9985. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9986. if (normalDotVelocity == 0) {
  9987. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9988. return;
  9989. embeddedInPlane = true;
  9990. t0 = 0;
  9991. }
  9992. else {
  9993. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9994. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9995. if (t0 > t1) {
  9996. var temp = t1;
  9997. t1 = t0;
  9998. t0 = temp;
  9999. }
  10000. if (t0 > 1.0 || t1 < 0.0)
  10001. return;
  10002. if (t0 < 0)
  10003. t0 = 0;
  10004. if (t0 > 1.0)
  10005. t0 = 1.0;
  10006. }
  10007. this._collisionPoint.copyFromFloats(0, 0, 0);
  10008. var found = false;
  10009. var t = 1.0;
  10010. if (!embeddedInPlane) {
  10011. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10012. this.velocity.scaleToRef(t0, this._tempVector);
  10013. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10014. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10015. found = true;
  10016. t = t0;
  10017. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10018. }
  10019. }
  10020. if (!found) {
  10021. var velocitySquaredLength = this.velocity.lengthSquared();
  10022. var a = velocitySquaredLength;
  10023. this.basePoint.subtractToRef(p1, this._tempVector);
  10024. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10025. var c = this._tempVector.lengthSquared() - 1.0;
  10026. var lowestRoot = getLowestRoot(a, b, c, t);
  10027. if (lowestRoot.found) {
  10028. t = lowestRoot.root;
  10029. found = true;
  10030. this._collisionPoint.copyFrom(p1);
  10031. }
  10032. this.basePoint.subtractToRef(p2, this._tempVector);
  10033. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10034. c = this._tempVector.lengthSquared() - 1.0;
  10035. lowestRoot = getLowestRoot(a, b, c, t);
  10036. if (lowestRoot.found) {
  10037. t = lowestRoot.root;
  10038. found = true;
  10039. this._collisionPoint.copyFrom(p2);
  10040. }
  10041. this.basePoint.subtractToRef(p3, this._tempVector);
  10042. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10043. c = this._tempVector.lengthSquared() - 1.0;
  10044. lowestRoot = getLowestRoot(a, b, c, t);
  10045. if (lowestRoot.found) {
  10046. t = lowestRoot.root;
  10047. found = true;
  10048. this._collisionPoint.copyFrom(p3);
  10049. }
  10050. p2.subtractToRef(p1, this._edge);
  10051. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10052. var edgeSquaredLength = this._edge.lengthSquared();
  10053. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10054. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10055. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10056. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10057. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10058. lowestRoot = getLowestRoot(a, b, c, t);
  10059. if (lowestRoot.found) {
  10060. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10061. if (f >= 0.0 && f <= 1.0) {
  10062. t = lowestRoot.root;
  10063. found = true;
  10064. this._edge.scaleInPlace(f);
  10065. p1.addToRef(this._edge, this._collisionPoint);
  10066. }
  10067. }
  10068. p3.subtractToRef(p2, this._edge);
  10069. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10070. edgeSquaredLength = this._edge.lengthSquared();
  10071. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10072. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10073. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10074. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10075. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10076. lowestRoot = getLowestRoot(a, b, c, t);
  10077. if (lowestRoot.found) {
  10078. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10079. if (f >= 0.0 && f <= 1.0) {
  10080. t = lowestRoot.root;
  10081. found = true;
  10082. this._edge.scaleInPlace(f);
  10083. p2.addToRef(this._edge, this._collisionPoint);
  10084. }
  10085. }
  10086. p1.subtractToRef(p3, this._edge);
  10087. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10088. edgeSquaredLength = this._edge.lengthSquared();
  10089. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10090. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10091. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10092. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10093. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10094. lowestRoot = getLowestRoot(a, b, c, t);
  10095. if (lowestRoot.found) {
  10096. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10097. if (f >= 0.0 && f <= 1.0) {
  10098. t = lowestRoot.root;
  10099. found = true;
  10100. this._edge.scaleInPlace(f);
  10101. p3.addToRef(this._edge, this._collisionPoint);
  10102. }
  10103. }
  10104. }
  10105. if (found) {
  10106. var distToCollision = t * this.velocity.length();
  10107. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10108. if (!this.intersectionPoint) {
  10109. this.intersectionPoint = this._collisionPoint.clone();
  10110. }
  10111. else {
  10112. this.intersectionPoint.copyFrom(this._collisionPoint);
  10113. }
  10114. this.nearestDistance = distToCollision;
  10115. this.collisionFound = true;
  10116. }
  10117. }
  10118. };
  10119. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10120. for (var i = indexStart; i < indexEnd; i += 3) {
  10121. var p1 = pts[indices[i] - decal];
  10122. var p2 = pts[indices[i + 1] - decal];
  10123. var p3 = pts[indices[i + 2] - decal];
  10124. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10125. }
  10126. };
  10127. Collider.prototype._getResponse = function (pos, vel) {
  10128. pos.addToRef(vel, this._destinationPoint);
  10129. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10130. this.basePoint.addToRef(vel, pos);
  10131. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10132. this._slidePlaneNormal.normalize();
  10133. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10134. pos.addInPlace(this._displacementVector);
  10135. this.intersectionPoint.addInPlace(this._displacementVector);
  10136. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10137. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10138. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10139. };
  10140. return Collider;
  10141. })();
  10142. BABYLON.Collider = Collider;
  10143. })(BABYLON || (BABYLON = {}));
  10144. var BABYLON;
  10145. (function (BABYLON) {
  10146. //WebWorker code will be inserted to this variable.
  10147. BABYLON.CollisionWorker = "";
  10148. (function (WorkerTaskType) {
  10149. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10150. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10151. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10152. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10153. var WorkerTaskType = BABYLON.WorkerTaskType;
  10154. (function (WorkerReplyType) {
  10155. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10156. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10157. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10158. var WorkerReplyType = BABYLON.WorkerReplyType;
  10159. var CollisionCoordinatorWorker = (function () {
  10160. function CollisionCoordinatorWorker() {
  10161. var _this = this;
  10162. this._scaledPosition = BABYLON.Vector3.Zero();
  10163. this._scaledVelocity = BABYLON.Vector3.Zero();
  10164. this.onMeshUpdated = function (mesh) {
  10165. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10166. };
  10167. this.onGeometryUpdated = function (geometry) {
  10168. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10169. };
  10170. this._afterRender = function () {
  10171. if (!_this._init)
  10172. return;
  10173. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10174. return;
  10175. }
  10176. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10177. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10178. if (_this._runningUpdated > 4) {
  10179. return;
  10180. }
  10181. ++_this._runningUpdated;
  10182. var payload = {
  10183. updatedMeshes: _this._addUpdateMeshesList,
  10184. updatedGeometries: _this._addUpdateGeometriesList,
  10185. removedGeometries: _this._toRemoveGeometryArray,
  10186. removedMeshes: _this._toRemoveMeshesArray
  10187. };
  10188. var message = {
  10189. payload: payload,
  10190. taskType: WorkerTaskType.UPDATE
  10191. };
  10192. var serializable = [];
  10193. for (var id in payload.updatedGeometries) {
  10194. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10195. //prepare transferables
  10196. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10197. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10198. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10199. }
  10200. }
  10201. _this._worker.postMessage(message, serializable);
  10202. _this._addUpdateMeshesList = {};
  10203. _this._addUpdateGeometriesList = {};
  10204. _this._toRemoveGeometryArray = [];
  10205. _this._toRemoveMeshesArray = [];
  10206. };
  10207. this._onMessageFromWorker = function (e) {
  10208. var returnData = e.data;
  10209. if (returnData.error != WorkerReplyType.SUCCESS) {
  10210. //TODO what errors can be returned from the worker?
  10211. BABYLON.Tools.Warn("error returned from worker!");
  10212. return;
  10213. }
  10214. switch (returnData.taskType) {
  10215. case WorkerTaskType.INIT:
  10216. _this._init = true;
  10217. //Update the worked with ALL of the scene's current state
  10218. _this._scene.meshes.forEach(function (mesh) {
  10219. _this.onMeshAdded(mesh);
  10220. });
  10221. _this._scene.getGeometries().forEach(function (geometry) {
  10222. _this.onGeometryAdded(geometry);
  10223. });
  10224. break;
  10225. case WorkerTaskType.UPDATE:
  10226. _this._runningUpdated--;
  10227. break;
  10228. case WorkerTaskType.COLLIDE:
  10229. _this._runningCollisionTask = false;
  10230. var returnPayload = returnData.payload;
  10231. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10232. return;
  10233. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10234. //cleanup
  10235. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10236. break;
  10237. }
  10238. };
  10239. this._collisionsCallbackArray = [];
  10240. this._init = false;
  10241. this._runningUpdated = 0;
  10242. this._runningCollisionTask = false;
  10243. this._addUpdateMeshesList = {};
  10244. this._addUpdateGeometriesList = {};
  10245. this._toRemoveGeometryArray = [];
  10246. this._toRemoveMeshesArray = [];
  10247. }
  10248. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10249. if (!this._init)
  10250. return;
  10251. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10252. return;
  10253. position.divideToRef(collider.radius, this._scaledPosition);
  10254. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10255. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10256. var payload = {
  10257. collider: {
  10258. position: this._scaledPosition.asArray(),
  10259. velocity: this._scaledVelocity.asArray(),
  10260. radius: collider.radius.asArray()
  10261. },
  10262. collisionId: collisionIndex,
  10263. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10264. maximumRetry: maximumRetry
  10265. };
  10266. var message = {
  10267. payload: payload,
  10268. taskType: WorkerTaskType.COLLIDE
  10269. };
  10270. this._worker.postMessage(message);
  10271. };
  10272. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10273. this._scene = scene;
  10274. this._scene.registerAfterRender(this._afterRender);
  10275. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10276. this._worker = new Worker(workerUrl);
  10277. this._worker.onmessage = this._onMessageFromWorker;
  10278. var message = {
  10279. payload: {},
  10280. taskType: WorkerTaskType.INIT
  10281. };
  10282. this._worker.postMessage(message);
  10283. };
  10284. CollisionCoordinatorWorker.prototype.destroy = function () {
  10285. this._scene.unregisterAfterRender(this._afterRender);
  10286. this._worker.terminate();
  10287. };
  10288. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10289. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10290. this.onMeshUpdated(mesh);
  10291. };
  10292. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10293. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10294. };
  10295. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10296. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10297. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10298. this.onGeometryUpdated(geometry);
  10299. };
  10300. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10301. this._toRemoveGeometryArray.push(geometry.id);
  10302. };
  10303. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10304. var submeshes = [];
  10305. if (mesh.subMeshes) {
  10306. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10307. return {
  10308. position: idx,
  10309. verticesStart: sm.verticesStart,
  10310. verticesCount: sm.verticesCount,
  10311. indexStart: sm.indexStart,
  10312. indexCount: sm.indexCount,
  10313. hasMaterial: !!sm.getMaterial(),
  10314. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10315. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10316. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10317. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10318. };
  10319. });
  10320. }
  10321. var geometryId = null;
  10322. if (mesh instanceof BABYLON.Mesh) {
  10323. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10324. }
  10325. else if (mesh instanceof BABYLON.InstancedMesh) {
  10326. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10327. }
  10328. return {
  10329. uniqueId: mesh.uniqueId,
  10330. id: mesh.id,
  10331. name: mesh.name,
  10332. geometryId: geometryId,
  10333. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10334. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10335. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10336. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10337. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10338. subMeshes: submeshes,
  10339. checkCollisions: mesh.checkCollisions
  10340. };
  10341. };
  10342. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10343. return {
  10344. id: geometry.id,
  10345. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10346. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10347. indices: new Int32Array(geometry.getIndices() || []),
  10348. };
  10349. };
  10350. return CollisionCoordinatorWorker;
  10351. })();
  10352. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10353. var CollisionCoordinatorLegacy = (function () {
  10354. function CollisionCoordinatorLegacy() {
  10355. this._scaledPosition = BABYLON.Vector3.Zero();
  10356. this._scaledVelocity = BABYLON.Vector3.Zero();
  10357. this._finalPosition = BABYLON.Vector3.Zero();
  10358. }
  10359. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10360. position.divideToRef(collider.radius, this._scaledPosition);
  10361. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10362. collider.collidedMesh = null;
  10363. collider.retry = 0;
  10364. collider.initialVelocity = this._scaledVelocity;
  10365. collider.initialPosition = this._scaledPosition;
  10366. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10367. this._finalPosition.multiplyInPlace(collider.radius);
  10368. //run the callback
  10369. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10370. };
  10371. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10372. this._scene = scene;
  10373. };
  10374. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10375. //Legacy need no destruction method.
  10376. };
  10377. //No update in legacy mode
  10378. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10379. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10380. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10381. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10382. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10383. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10384. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10385. if (excludedMesh === void 0) { excludedMesh = null; }
  10386. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10387. if (collider.retry >= maximumRetry) {
  10388. finalPosition.copyFrom(position);
  10389. return;
  10390. }
  10391. collider._initialize(position, velocity, closeDistance);
  10392. // Check all meshes
  10393. for (var index = 0; index < this._scene.meshes.length; index++) {
  10394. var mesh = this._scene.meshes[index];
  10395. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10396. mesh._checkCollision(collider);
  10397. }
  10398. }
  10399. if (!collider.collisionFound) {
  10400. position.addToRef(velocity, finalPosition);
  10401. return;
  10402. }
  10403. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10404. collider._getResponse(position, velocity);
  10405. }
  10406. if (velocity.length() <= closeDistance) {
  10407. finalPosition.copyFrom(position);
  10408. return;
  10409. }
  10410. collider.retry++;
  10411. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10412. };
  10413. return CollisionCoordinatorLegacy;
  10414. })();
  10415. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10416. })(BABYLON || (BABYLON = {}));
  10417. var BABYLON;
  10418. (function (BABYLON) {
  10419. var Camera = (function (_super) {
  10420. __extends(Camera, _super);
  10421. function Camera(name, position, scene) {
  10422. _super.call(this, name, scene);
  10423. this.upVector = BABYLON.Vector3.Up();
  10424. this.orthoLeft = null;
  10425. this.orthoRight = null;
  10426. this.orthoBottom = null;
  10427. this.orthoTop = null;
  10428. this.fov = 0.8;
  10429. this.minZ = 1.0;
  10430. this.maxZ = 10000.0;
  10431. this.inertia = 0.9;
  10432. this.mode = Camera.PERSPECTIVE_CAMERA;
  10433. this.isIntermediate = false;
  10434. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10435. this.layerMask = 0x0FFFFFFF;
  10436. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10437. // Camera rig members
  10438. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10439. this._rigCameras = new Array();
  10440. // Cache
  10441. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10442. this._projectionMatrix = new BABYLON.Matrix();
  10443. this._postProcesses = new Array();
  10444. this._postProcessesTakenIndices = [];
  10445. this._activeMeshes = new BABYLON.SmartArray(256);
  10446. this._globalPosition = BABYLON.Vector3.Zero();
  10447. scene.addCamera(this);
  10448. if (!scene.activeCamera) {
  10449. scene.activeCamera = this;
  10450. }
  10451. this.position = position;
  10452. }
  10453. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10454. get: function () {
  10455. return Camera._PERSPECTIVE_CAMERA;
  10456. },
  10457. enumerable: true,
  10458. configurable: true
  10459. });
  10460. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10461. get: function () {
  10462. return Camera._ORTHOGRAPHIC_CAMERA;
  10463. },
  10464. enumerable: true,
  10465. configurable: true
  10466. });
  10467. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10468. get: function () {
  10469. return Camera._FOVMODE_VERTICAL_FIXED;
  10470. },
  10471. enumerable: true,
  10472. configurable: true
  10473. });
  10474. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10475. get: function () {
  10476. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10477. },
  10478. enumerable: true,
  10479. configurable: true
  10480. });
  10481. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10482. get: function () {
  10483. return Camera._RIG_MODE_NONE;
  10484. },
  10485. enumerable: true,
  10486. configurable: true
  10487. });
  10488. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10489. get: function () {
  10490. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10491. },
  10492. enumerable: true,
  10493. configurable: true
  10494. });
  10495. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10496. get: function () {
  10497. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10498. },
  10499. enumerable: true,
  10500. configurable: true
  10501. });
  10502. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10503. get: function () {
  10504. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10505. },
  10506. enumerable: true,
  10507. configurable: true
  10508. });
  10509. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10510. get: function () {
  10511. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10512. },
  10513. enumerable: true,
  10514. configurable: true
  10515. });
  10516. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10517. get: function () {
  10518. return Camera._RIG_MODE_VR;
  10519. },
  10520. enumerable: true,
  10521. configurable: true
  10522. });
  10523. Object.defineProperty(Camera.prototype, "globalPosition", {
  10524. get: function () {
  10525. return this._globalPosition;
  10526. },
  10527. enumerable: true,
  10528. configurable: true
  10529. });
  10530. Camera.prototype.getActiveMeshes = function () {
  10531. return this._activeMeshes;
  10532. };
  10533. Camera.prototype.isActiveMesh = function (mesh) {
  10534. return (this._activeMeshes.indexOf(mesh) !== -1);
  10535. };
  10536. //Cache
  10537. Camera.prototype._initCache = function () {
  10538. _super.prototype._initCache.call(this);
  10539. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10540. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10541. this._cache.mode = undefined;
  10542. this._cache.minZ = undefined;
  10543. this._cache.maxZ = undefined;
  10544. this._cache.fov = undefined;
  10545. this._cache.aspectRatio = undefined;
  10546. this._cache.orthoLeft = undefined;
  10547. this._cache.orthoRight = undefined;
  10548. this._cache.orthoBottom = undefined;
  10549. this._cache.orthoTop = undefined;
  10550. this._cache.renderWidth = undefined;
  10551. this._cache.renderHeight = undefined;
  10552. };
  10553. Camera.prototype._updateCache = function (ignoreParentClass) {
  10554. if (!ignoreParentClass) {
  10555. _super.prototype._updateCache.call(this);
  10556. }
  10557. var engine = this.getEngine();
  10558. this._cache.position.copyFrom(this.position);
  10559. this._cache.upVector.copyFrom(this.upVector);
  10560. this._cache.mode = this.mode;
  10561. this._cache.minZ = this.minZ;
  10562. this._cache.maxZ = this.maxZ;
  10563. this._cache.fov = this.fov;
  10564. this._cache.aspectRatio = engine.getAspectRatio(this);
  10565. this._cache.orthoLeft = this.orthoLeft;
  10566. this._cache.orthoRight = this.orthoRight;
  10567. this._cache.orthoBottom = this.orthoBottom;
  10568. this._cache.orthoTop = this.orthoTop;
  10569. this._cache.renderWidth = engine.getRenderWidth();
  10570. this._cache.renderHeight = engine.getRenderHeight();
  10571. };
  10572. Camera.prototype._updateFromScene = function () {
  10573. this.updateCache();
  10574. this._update();
  10575. };
  10576. // Synchronized
  10577. Camera.prototype._isSynchronized = function () {
  10578. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10579. };
  10580. Camera.prototype._isSynchronizedViewMatrix = function () {
  10581. if (!_super.prototype._isSynchronized.call(this))
  10582. return false;
  10583. return this._cache.position.equals(this.position)
  10584. && this._cache.upVector.equals(this.upVector)
  10585. && this.isSynchronizedWithParent();
  10586. };
  10587. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10588. var check = this._cache.mode === this.mode
  10589. && this._cache.minZ === this.minZ
  10590. && this._cache.maxZ === this.maxZ;
  10591. if (!check) {
  10592. return false;
  10593. }
  10594. var engine = this.getEngine();
  10595. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10596. check = this._cache.fov === this.fov
  10597. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10598. }
  10599. else {
  10600. check = this._cache.orthoLeft === this.orthoLeft
  10601. && this._cache.orthoRight === this.orthoRight
  10602. && this._cache.orthoBottom === this.orthoBottom
  10603. && this._cache.orthoTop === this.orthoTop
  10604. && this._cache.renderWidth === engine.getRenderWidth()
  10605. && this._cache.renderHeight === engine.getRenderHeight();
  10606. }
  10607. return check;
  10608. };
  10609. // Controls
  10610. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10611. };
  10612. Camera.prototype.detachControl = function (element) {
  10613. };
  10614. Camera.prototype._update = function () {
  10615. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10616. this._updateRigCameras();
  10617. }
  10618. this._checkInputs();
  10619. };
  10620. Camera.prototype._checkInputs = function () {
  10621. };
  10622. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10623. if (insertAt === void 0) { insertAt = null; }
  10624. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10625. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10626. return 0;
  10627. }
  10628. if (insertAt == null || insertAt < 0) {
  10629. this._postProcesses.push(postProcess);
  10630. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10631. return this._postProcesses.length - 1;
  10632. }
  10633. var add = 0;
  10634. var i;
  10635. var start;
  10636. if (this._postProcesses[insertAt]) {
  10637. start = this._postProcesses.length - 1;
  10638. for (i = start; i >= insertAt + 1; --i) {
  10639. this._postProcesses[i + 1] = this._postProcesses[i];
  10640. }
  10641. add = 1;
  10642. }
  10643. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10644. if (this._postProcessesTakenIndices[i] < insertAt) {
  10645. continue;
  10646. }
  10647. start = this._postProcessesTakenIndices.length - 1;
  10648. for (var j = start; j >= i; --j) {
  10649. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10650. }
  10651. this._postProcessesTakenIndices[i] = insertAt;
  10652. break;
  10653. }
  10654. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10655. this._postProcessesTakenIndices.push(insertAt);
  10656. }
  10657. var result = insertAt + add;
  10658. this._postProcesses[result] = postProcess;
  10659. return result;
  10660. };
  10661. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10662. if (atIndices === void 0) { atIndices = null; }
  10663. var result = [];
  10664. var i;
  10665. var index;
  10666. if (!atIndices) {
  10667. var length = this._postProcesses.length;
  10668. for (i = 0; i < length; i++) {
  10669. if (this._postProcesses[i] !== postProcess) {
  10670. continue;
  10671. }
  10672. delete this._postProcesses[i];
  10673. index = this._postProcessesTakenIndices.indexOf(i);
  10674. this._postProcessesTakenIndices.splice(index, 1);
  10675. }
  10676. }
  10677. else {
  10678. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10679. for (i = 0; i < atIndices.length; i++) {
  10680. var foundPostProcess = this._postProcesses[atIndices[i]];
  10681. if (foundPostProcess !== postProcess) {
  10682. result.push(i);
  10683. continue;
  10684. }
  10685. delete this._postProcesses[atIndices[i]];
  10686. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10687. this._postProcessesTakenIndices.splice(index, 1);
  10688. }
  10689. }
  10690. return result;
  10691. };
  10692. Camera.prototype.getWorldMatrix = function () {
  10693. if (!this._worldMatrix) {
  10694. this._worldMatrix = BABYLON.Matrix.Identity();
  10695. }
  10696. var viewMatrix = this.getViewMatrix();
  10697. viewMatrix.invertToRef(this._worldMatrix);
  10698. return this._worldMatrix;
  10699. };
  10700. Camera.prototype._getViewMatrix = function () {
  10701. return BABYLON.Matrix.Identity();
  10702. };
  10703. Camera.prototype.getViewMatrix = function (force) {
  10704. this._computedViewMatrix = this._computeViewMatrix(force);
  10705. if (!force && this._isSynchronizedViewMatrix()) {
  10706. return this._computedViewMatrix;
  10707. }
  10708. if (!this.parent || !this.parent.getWorldMatrix) {
  10709. this._globalPosition.copyFrom(this.position);
  10710. }
  10711. else {
  10712. if (!this._worldMatrix) {
  10713. this._worldMatrix = BABYLON.Matrix.Identity();
  10714. }
  10715. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10716. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10717. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10718. this._computedViewMatrix.invert();
  10719. this._markSyncedWithParent();
  10720. }
  10721. this._currentRenderId = this.getScene().getRenderId();
  10722. return this._computedViewMatrix;
  10723. };
  10724. Camera.prototype._computeViewMatrix = function (force) {
  10725. if (!force && this._isSynchronizedViewMatrix()) {
  10726. return this._computedViewMatrix;
  10727. }
  10728. this._computedViewMatrix = this._getViewMatrix();
  10729. this._currentRenderId = this.getScene().getRenderId();
  10730. return this._computedViewMatrix;
  10731. };
  10732. Camera.prototype.getProjectionMatrix = function (force) {
  10733. if (!force && this._isSynchronizedProjectionMatrix()) {
  10734. return this._projectionMatrix;
  10735. }
  10736. var engine = this.getEngine();
  10737. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10738. if (this.minZ <= 0) {
  10739. this.minZ = 0.1;
  10740. }
  10741. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10742. return this._projectionMatrix;
  10743. }
  10744. var halfWidth = engine.getRenderWidth() / 2.0;
  10745. var halfHeight = engine.getRenderHeight() / 2.0;
  10746. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10747. return this._projectionMatrix;
  10748. };
  10749. Camera.prototype.dispose = function () {
  10750. // Animations
  10751. this.getScene().stopAnimation(this);
  10752. // Remove from scene
  10753. this.getScene().removeCamera(this);
  10754. while (this._rigCameras.length > 0) {
  10755. this._rigCameras.pop().dispose();
  10756. }
  10757. // Postprocesses
  10758. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10759. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10760. }
  10761. };
  10762. // ---- Camera rigs section ----
  10763. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10764. while (this._rigCameras.length > 0) {
  10765. this._rigCameras.pop().dispose();
  10766. }
  10767. this.cameraRigMode = mode;
  10768. this._cameraRigParams = {};
  10769. switch (this.cameraRigMode) {
  10770. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10771. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10772. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10773. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10774. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10775. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10776. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10777. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10778. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10779. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10780. break;
  10781. }
  10782. var postProcesses = new Array();
  10783. switch (this.cameraRigMode) {
  10784. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10785. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10786. this._rigCameras[0].isIntermediate = true;
  10787. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10788. postProcesses[1].onApply = function (effect) {
  10789. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10790. };
  10791. break;
  10792. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10793. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10794. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10795. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10796. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10797. var secondCamIndex = 1 - firstCamIndex;
  10798. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10799. this._rigCameras[firstCamIndex].isIntermediate = true;
  10800. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10801. break;
  10802. case Camera.RIG_MODE_VR:
  10803. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10804. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10805. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10806. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10807. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10808. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10809. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10810. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10811. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10812. if (metrics.compensateDistortion) {
  10813. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10814. }
  10815. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10816. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10817. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10818. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10819. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10820. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10821. if (metrics.compensateDistortion) {
  10822. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10823. }
  10824. break;
  10825. }
  10826. this._update();
  10827. };
  10828. Camera.prototype._getVRProjectionMatrix = function () {
  10829. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10830. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10831. return this._projectionMatrix;
  10832. };
  10833. Camera.prototype.setCameraRigParameter = function (name, value) {
  10834. this._cameraRigParams[name] = value;
  10835. //provisionnally:
  10836. if (name === "interaxialDistance") {
  10837. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10838. }
  10839. };
  10840. /**
  10841. * May needs to be overridden by children so sub has required properties to be copied
  10842. */
  10843. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10844. return null;
  10845. };
  10846. /**
  10847. * May needs to be overridden by children
  10848. */
  10849. Camera.prototype._updateRigCameras = function () {
  10850. for (var i = 0; i < this._rigCameras.length; i++) {
  10851. this._rigCameras[i].minZ = this.minZ;
  10852. this._rigCameras[i].maxZ = this.maxZ;
  10853. this._rigCameras[i].fov = this.fov;
  10854. }
  10855. // only update viewport when ANAGLYPH
  10856. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10857. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10858. }
  10859. };
  10860. Camera.prototype.serialize = function () {
  10861. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10862. // Type
  10863. serializationObject.type = this.getTypeName();
  10864. // Parent
  10865. if (this.parent) {
  10866. serializationObject.parentId = this.parent.id;
  10867. }
  10868. // Animations
  10869. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10870. serializationObject.ranges = this.serializeAnimationRanges();
  10871. return serializationObject;
  10872. };
  10873. Camera.prototype.getTypeName = function () {
  10874. return "Camera";
  10875. };
  10876. Camera.prototype.clone = function (name) {
  10877. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10878. };
  10879. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10880. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10881. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10882. switch (type) {
  10883. case "ArcRotateCamera":
  10884. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10885. case "DeviceOrientationCamera":
  10886. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10887. case "FollowCamera":
  10888. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10889. case "ArcFollowCamera":
  10890. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10891. case "GamepadCamera":
  10892. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10893. case "TouchCamera":
  10894. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10895. case "VirtualJoysticksCamera":
  10896. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10897. case "WebVRFreeCamera":
  10898. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10899. case "VRDeviceOrientationFreeCamera":
  10900. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10901. case "AnaglyphArcRotateCamera":
  10902. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10903. case "AnaglyphFreeCamera":
  10904. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10905. case "AnaglyphGamepadCamera":
  10906. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10907. case "AnaglyphUniversalCamera":
  10908. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10909. case "StereoscopicArcRotateCamera":
  10910. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10911. case "StereoscopicFreeCamera":
  10912. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10913. case "StereoscopicGamepadCamera":
  10914. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10915. case "StereoscopicUniversalCamera":
  10916. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10917. case "FreeCamera":
  10918. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10919. default:
  10920. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10921. }
  10922. };
  10923. Camera.Parse = function (parsedCamera, scene) {
  10924. var type = parsedCamera.type;
  10925. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10926. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10927. // Parent
  10928. if (parsedCamera.parentId) {
  10929. camera._waitingParentId = parsedCamera.parentId;
  10930. }
  10931. // Target
  10932. if (parsedCamera.target) {
  10933. if (camera.setTarget) {
  10934. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10935. }
  10936. }
  10937. // Apply 3d rig, when found
  10938. if (parsedCamera.cameraRigMode) {
  10939. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10940. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10941. }
  10942. // Animations
  10943. if (parsedCamera.animations) {
  10944. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10945. var parsedAnimation = parsedCamera.animations[animationIndex];
  10946. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10947. }
  10948. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10949. }
  10950. if (parsedCamera.autoAnimate) {
  10951. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10952. }
  10953. return camera;
  10954. };
  10955. // Statics
  10956. Camera._PERSPECTIVE_CAMERA = 0;
  10957. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10958. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10959. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10960. Camera._RIG_MODE_NONE = 0;
  10961. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10962. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10963. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10964. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10965. Camera._RIG_MODE_VR = 20;
  10966. __decorate([
  10967. BABYLON.serializeAsVector3()
  10968. ], Camera.prototype, "position", void 0);
  10969. __decorate([
  10970. BABYLON.serialize()
  10971. ], Camera.prototype, "upVector", void 0);
  10972. __decorate([
  10973. BABYLON.serialize()
  10974. ], Camera.prototype, "orthoLeft", void 0);
  10975. __decorate([
  10976. BABYLON.serialize()
  10977. ], Camera.prototype, "orthoRight", void 0);
  10978. __decorate([
  10979. BABYLON.serialize()
  10980. ], Camera.prototype, "orthoBottom", void 0);
  10981. __decorate([
  10982. BABYLON.serialize()
  10983. ], Camera.prototype, "orthoTop", void 0);
  10984. __decorate([
  10985. BABYLON.serialize()
  10986. ], Camera.prototype, "fov", void 0);
  10987. __decorate([
  10988. BABYLON.serialize()
  10989. ], Camera.prototype, "minZ", void 0);
  10990. __decorate([
  10991. BABYLON.serialize()
  10992. ], Camera.prototype, "maxZ", void 0);
  10993. __decorate([
  10994. BABYLON.serialize()
  10995. ], Camera.prototype, "inertia", void 0);
  10996. __decorate([
  10997. BABYLON.serialize()
  10998. ], Camera.prototype, "mode", void 0);
  10999. __decorate([
  11000. BABYLON.serialize()
  11001. ], Camera.prototype, "layerMask", void 0);
  11002. __decorate([
  11003. BABYLON.serialize()
  11004. ], Camera.prototype, "fovMode", void 0);
  11005. __decorate([
  11006. BABYLON.serialize()
  11007. ], Camera.prototype, "cameraRigMode", void 0);
  11008. __decorate([
  11009. BABYLON.serialize()
  11010. ], Camera.prototype, "interaxialDistance", void 0);
  11011. __decorate([
  11012. BABYLON.serialize()
  11013. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11014. return Camera;
  11015. })(BABYLON.Node);
  11016. BABYLON.Camera = Camera;
  11017. })(BABYLON || (BABYLON = {}));
  11018. var BABYLON;
  11019. (function (BABYLON) {
  11020. var TargetCamera = (function (_super) {
  11021. __extends(TargetCamera, _super);
  11022. function TargetCamera(name, position, scene) {
  11023. _super.call(this, name, position, scene);
  11024. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11025. this.cameraRotation = new BABYLON.Vector2(0, 0);
  11026. this.rotation = new BABYLON.Vector3(0, 0, 0);
  11027. this.speed = 2.0;
  11028. this.noRotationConstraint = false;
  11029. this.lockedTarget = null;
  11030. this._currentTarget = BABYLON.Vector3.Zero();
  11031. this._viewMatrix = BABYLON.Matrix.Zero();
  11032. this._camMatrix = BABYLON.Matrix.Zero();
  11033. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  11034. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  11035. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  11036. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  11037. this._lookAtTemp = BABYLON.Matrix.Zero();
  11038. this._tempMatrix = BABYLON.Matrix.Zero();
  11039. }
  11040. TargetCamera.prototype.getFrontPosition = function (distance) {
  11041. var direction = this.getTarget().subtract(this.position);
  11042. direction.normalize();
  11043. direction.scaleInPlace(distance);
  11044. return this.globalPosition.add(direction);
  11045. };
  11046. TargetCamera.prototype._getLockedTargetPosition = function () {
  11047. if (!this.lockedTarget) {
  11048. return null;
  11049. }
  11050. return this.lockedTarget.position || this.lockedTarget;
  11051. };
  11052. // Cache
  11053. TargetCamera.prototype._initCache = function () {
  11054. _super.prototype._initCache.call(this);
  11055. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11056. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11057. };
  11058. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  11059. if (!ignoreParentClass) {
  11060. _super.prototype._updateCache.call(this);
  11061. }
  11062. var lockedTargetPosition = this._getLockedTargetPosition();
  11063. if (!lockedTargetPosition) {
  11064. this._cache.lockedTarget = null;
  11065. }
  11066. else {
  11067. if (!this._cache.lockedTarget) {
  11068. this._cache.lockedTarget = lockedTargetPosition.clone();
  11069. }
  11070. else {
  11071. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  11072. }
  11073. }
  11074. this._cache.rotation.copyFrom(this.rotation);
  11075. };
  11076. // Synchronized
  11077. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  11078. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  11079. return false;
  11080. }
  11081. var lockedTargetPosition = this._getLockedTargetPosition();
  11082. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  11083. && this._cache.rotation.equals(this.rotation);
  11084. };
  11085. // Methods
  11086. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  11087. var engine = this.getEngine();
  11088. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  11089. };
  11090. // Target
  11091. TargetCamera.prototype.setTarget = function (target) {
  11092. this.upVector.normalize();
  11093. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  11094. this._camMatrix.invert();
  11095. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  11096. var vDir = target.subtract(this.position);
  11097. if (vDir.x >= 0.0) {
  11098. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  11099. }
  11100. else {
  11101. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  11102. }
  11103. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  11104. if (isNaN(this.rotation.x)) {
  11105. this.rotation.x = 0;
  11106. }
  11107. if (isNaN(this.rotation.y)) {
  11108. this.rotation.y = 0;
  11109. }
  11110. if (isNaN(this.rotation.z)) {
  11111. this.rotation.z = 0;
  11112. }
  11113. };
  11114. TargetCamera.prototype.getTarget = function () {
  11115. return this._currentTarget;
  11116. };
  11117. TargetCamera.prototype._decideIfNeedsToMove = function () {
  11118. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11119. };
  11120. TargetCamera.prototype._updatePosition = function () {
  11121. this.position.addInPlace(this.cameraDirection);
  11122. };
  11123. TargetCamera.prototype._checkInputs = function () {
  11124. var needToMove = this._decideIfNeedsToMove();
  11125. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  11126. // Move
  11127. if (needToMove) {
  11128. this._updatePosition();
  11129. }
  11130. // Rotate
  11131. if (needToRotate) {
  11132. this.rotation.x += this.cameraRotation.x;
  11133. this.rotation.y += this.cameraRotation.y;
  11134. if (!this.noRotationConstraint) {
  11135. var limit = (Math.PI / 2) * 0.95;
  11136. if (this.rotation.x > limit)
  11137. this.rotation.x = limit;
  11138. if (this.rotation.x < -limit)
  11139. this.rotation.x = -limit;
  11140. }
  11141. }
  11142. // Inertia
  11143. if (needToMove) {
  11144. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  11145. this.cameraDirection.x = 0;
  11146. }
  11147. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  11148. this.cameraDirection.y = 0;
  11149. }
  11150. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  11151. this.cameraDirection.z = 0;
  11152. }
  11153. this.cameraDirection.scaleInPlace(this.inertia);
  11154. }
  11155. if (needToRotate) {
  11156. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  11157. this.cameraRotation.x = 0;
  11158. }
  11159. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  11160. this.cameraRotation.y = 0;
  11161. }
  11162. this.cameraRotation.scaleInPlace(this.inertia);
  11163. }
  11164. _super.prototype._checkInputs.call(this);
  11165. };
  11166. TargetCamera.prototype._getViewMatrix = function () {
  11167. if (!this.lockedTarget) {
  11168. // Compute
  11169. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  11170. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  11171. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11172. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  11173. this._lookAtTemp.invert();
  11174. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  11175. }
  11176. else {
  11177. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11178. }
  11179. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11180. // Computing target and final matrix
  11181. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11182. }
  11183. else {
  11184. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  11185. }
  11186. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  11187. return this._viewMatrix;
  11188. };
  11189. TargetCamera.prototype._getVRViewMatrix = function () {
  11190. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11191. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11192. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  11193. // Computing target and final matrix
  11194. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11195. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  11196. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  11197. return this._viewMatrix;
  11198. };
  11199. /**
  11200. * @override
  11201. * Override Camera.createRigCamera
  11202. */
  11203. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11204. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  11205. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  11206. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11207. rigCamera._cameraRigParams = {};
  11208. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  11209. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  11210. }
  11211. return rigCamera;
  11212. }
  11213. return null;
  11214. };
  11215. /**
  11216. * @override
  11217. * Override Camera._updateRigCameras
  11218. */
  11219. TargetCamera.prototype._updateRigCameras = function () {
  11220. switch (this.cameraRigMode) {
  11221. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11222. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11223. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11224. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11225. case BABYLON.Camera.RIG_MODE_VR:
  11226. var camLeft = this._rigCameras[0];
  11227. var camRight = this._rigCameras[1];
  11228. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11229. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  11230. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  11231. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  11232. camLeft.position.copyFrom(this.position);
  11233. camRight.position.copyFrom(this.position);
  11234. }
  11235. else {
  11236. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11237. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11238. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11239. camLeft.setTarget(this.getTarget());
  11240. camRight.setTarget(this.getTarget());
  11241. }
  11242. break;
  11243. }
  11244. _super.prototype._updateRigCameras.call(this);
  11245. };
  11246. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11247. if (!this._rigCamTransformMatrix) {
  11248. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11249. }
  11250. var target = this.getTarget();
  11251. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11252. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11253. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11254. };
  11255. TargetCamera.prototype.getTypeName = function () {
  11256. return "TargetCamera";
  11257. };
  11258. __decorate([
  11259. BABYLON.serializeAsVector3()
  11260. ], TargetCamera.prototype, "rotation", void 0);
  11261. __decorate([
  11262. BABYLON.serialize()
  11263. ], TargetCamera.prototype, "speed", void 0);
  11264. __decorate([
  11265. BABYLON.serializeAsMeshReference("lockedTargetId")
  11266. ], TargetCamera.prototype, "lockedTarget", void 0);
  11267. return TargetCamera;
  11268. })(BABYLON.Camera);
  11269. BABYLON.TargetCamera = TargetCamera;
  11270. })(BABYLON || (BABYLON = {}));
  11271. var BABYLON;
  11272. (function (BABYLON) {
  11273. var FreeCamera = (function (_super) {
  11274. __extends(FreeCamera, _super);
  11275. function FreeCamera(name, position, scene) {
  11276. var _this = this;
  11277. _super.call(this, name, position, scene);
  11278. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11279. this.keysUp = [38];
  11280. this.keysDown = [40];
  11281. this.keysLeft = [37];
  11282. this.keysRight = [39];
  11283. this.checkCollisions = false;
  11284. this.applyGravity = false;
  11285. this.angularSensibility = 2000.0;
  11286. this._keys = [];
  11287. this._collider = new BABYLON.Collider();
  11288. this._needMoveForGravity = false;
  11289. this._oldPosition = BABYLON.Vector3.Zero();
  11290. this._diffPosition = BABYLON.Vector3.Zero();
  11291. this._newPosition = BABYLON.Vector3.Zero();
  11292. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11293. if (collidedMesh === void 0) { collidedMesh = null; }
  11294. //TODO move this to the collision coordinator!
  11295. if (_this.getScene().workerCollisions)
  11296. newPosition.multiplyInPlace(_this._collider.radius);
  11297. var updatePosition = function (newPos) {
  11298. _this._newPosition.copyFrom(newPos);
  11299. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11300. var oldPosition = _this.position.clone();
  11301. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11302. _this.position.addInPlace(_this._diffPosition);
  11303. if (_this.onCollide && collidedMesh) {
  11304. _this.onCollide(collidedMesh);
  11305. }
  11306. }
  11307. };
  11308. updatePosition(newPosition);
  11309. };
  11310. }
  11311. FreeCamera.prototype._onLostFocus = function (e) {
  11312. this._keys = [];
  11313. };
  11314. // Controls
  11315. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11316. var _this = this;
  11317. var previousPosition;
  11318. var engine = this.getEngine();
  11319. if (this._attachedElement) {
  11320. return;
  11321. }
  11322. this._attachedElement = element;
  11323. if (this._onMouseDown === undefined) {
  11324. this._onMouseDown = function (evt) {
  11325. previousPosition = {
  11326. x: evt.clientX,
  11327. y: evt.clientY
  11328. };
  11329. if (!noPreventDefault) {
  11330. evt.preventDefault();
  11331. }
  11332. };
  11333. this._onMouseUp = function (evt) {
  11334. previousPosition = null;
  11335. if (!noPreventDefault) {
  11336. evt.preventDefault();
  11337. }
  11338. };
  11339. this._onMouseOut = function (evt) {
  11340. previousPosition = null;
  11341. _this._keys = [];
  11342. if (!noPreventDefault) {
  11343. evt.preventDefault();
  11344. }
  11345. };
  11346. this._onMouseMove = function (evt) {
  11347. if (!previousPosition && !engine.isPointerLock) {
  11348. return;
  11349. }
  11350. var offsetX;
  11351. var offsetY;
  11352. if (!engine.isPointerLock) {
  11353. offsetX = evt.clientX - previousPosition.x;
  11354. offsetY = evt.clientY - previousPosition.y;
  11355. }
  11356. else {
  11357. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11358. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11359. }
  11360. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11361. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11362. previousPosition = {
  11363. x: evt.clientX,
  11364. y: evt.clientY
  11365. };
  11366. if (!noPreventDefault) {
  11367. evt.preventDefault();
  11368. }
  11369. };
  11370. this._onKeyDown = function (evt) {
  11371. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11372. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11373. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11374. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11375. var index = _this._keys.indexOf(evt.keyCode);
  11376. if (index === -1) {
  11377. _this._keys.push(evt.keyCode);
  11378. }
  11379. if (!noPreventDefault) {
  11380. evt.preventDefault();
  11381. }
  11382. }
  11383. };
  11384. this._onKeyUp = function (evt) {
  11385. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11386. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11387. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11388. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11389. var index = _this._keys.indexOf(evt.keyCode);
  11390. if (index >= 0) {
  11391. _this._keys.splice(index, 1);
  11392. }
  11393. if (!noPreventDefault) {
  11394. evt.preventDefault();
  11395. }
  11396. }
  11397. };
  11398. this._reset = function () {
  11399. _this._keys = [];
  11400. previousPosition = null;
  11401. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11402. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11403. };
  11404. }
  11405. element.addEventListener("mousedown", this._onMouseDown, false);
  11406. element.addEventListener("mouseup", this._onMouseUp, false);
  11407. element.addEventListener("mouseout", this._onMouseOut, false);
  11408. element.addEventListener("mousemove", this._onMouseMove, false);
  11409. BABYLON.Tools.RegisterTopRootEvents([
  11410. { name: "keydown", handler: this._onKeyDown },
  11411. { name: "keyup", handler: this._onKeyUp },
  11412. { name: "blur", handler: this._onLostFocus }
  11413. ]);
  11414. };
  11415. FreeCamera.prototype.detachControl = function (element) {
  11416. if (this._attachedElement !== element) {
  11417. return;
  11418. }
  11419. element.removeEventListener("mousedown", this._onMouseDown);
  11420. element.removeEventListener("mouseup", this._onMouseUp);
  11421. element.removeEventListener("mouseout", this._onMouseOut);
  11422. element.removeEventListener("mousemove", this._onMouseMove);
  11423. BABYLON.Tools.UnregisterTopRootEvents([
  11424. { name: "keydown", handler: this._onKeyDown },
  11425. { name: "keyup", handler: this._onKeyUp },
  11426. { name: "blur", handler: this._onLostFocus }
  11427. ]);
  11428. this._attachedElement = null;
  11429. if (this._reset) {
  11430. this._reset();
  11431. }
  11432. };
  11433. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11434. var globalPosition;
  11435. if (this.parent) {
  11436. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11437. }
  11438. else {
  11439. globalPosition = this.position;
  11440. }
  11441. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11442. this._collider.radius = this.ellipsoid;
  11443. //no need for clone, as long as gravity is not on.
  11444. var actualVelocity = velocity;
  11445. //add gravity to the velocity to prevent the dual-collision checking
  11446. if (this.applyGravity) {
  11447. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11448. actualVelocity = velocity.add(this.getScene().gravity);
  11449. }
  11450. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11451. };
  11452. FreeCamera.prototype._checkInputs = function () {
  11453. if (!this._localDirection) {
  11454. this._localDirection = BABYLON.Vector3.Zero();
  11455. this._transformedDirection = BABYLON.Vector3.Zero();
  11456. }
  11457. // Keyboard
  11458. for (var index = 0; index < this._keys.length; index++) {
  11459. var keyCode = this._keys[index];
  11460. var speed = this._computeLocalCameraSpeed();
  11461. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11462. this._localDirection.copyFromFloats(-speed, 0, 0);
  11463. }
  11464. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11465. this._localDirection.copyFromFloats(0, 0, speed);
  11466. }
  11467. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11468. this._localDirection.copyFromFloats(speed, 0, 0);
  11469. }
  11470. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11471. this._localDirection.copyFromFloats(0, 0, -speed);
  11472. }
  11473. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11474. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11475. this.cameraDirection.addInPlace(this._transformedDirection);
  11476. }
  11477. _super.prototype._checkInputs.call(this);
  11478. };
  11479. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11480. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11481. };
  11482. FreeCamera.prototype._updatePosition = function () {
  11483. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11484. this._collideWithWorld(this.cameraDirection);
  11485. }
  11486. else {
  11487. this.position.addInPlace(this.cameraDirection);
  11488. }
  11489. };
  11490. FreeCamera.prototype.getTypeName = function () {
  11491. return "FreeCamera";
  11492. };
  11493. __decorate([
  11494. BABYLON.serializeAsVector3()
  11495. ], FreeCamera.prototype, "ellipsoid", void 0);
  11496. __decorate([
  11497. BABYLON.serialize()
  11498. ], FreeCamera.prototype, "keysUp", void 0);
  11499. __decorate([
  11500. BABYLON.serialize()
  11501. ], FreeCamera.prototype, "keysDown", void 0);
  11502. __decorate([
  11503. BABYLON.serialize()
  11504. ], FreeCamera.prototype, "keysLeft", void 0);
  11505. __decorate([
  11506. BABYLON.serialize()
  11507. ], FreeCamera.prototype, "keysRight", void 0);
  11508. __decorate([
  11509. BABYLON.serialize()
  11510. ], FreeCamera.prototype, "checkCollisions", void 0);
  11511. __decorate([
  11512. BABYLON.serialize()
  11513. ], FreeCamera.prototype, "applyGravity", void 0);
  11514. __decorate([
  11515. BABYLON.serialize()
  11516. ], FreeCamera.prototype, "angularSensibility", void 0);
  11517. return FreeCamera;
  11518. })(BABYLON.TargetCamera);
  11519. BABYLON.FreeCamera = FreeCamera;
  11520. })(BABYLON || (BABYLON = {}));
  11521. var BABYLON;
  11522. (function (BABYLON) {
  11523. var FollowCamera = (function (_super) {
  11524. __extends(FollowCamera, _super);
  11525. function FollowCamera(name, position, scene, target) {
  11526. _super.call(this, name, position, scene);
  11527. this.radius = 12;
  11528. this.rotationOffset = 0;
  11529. this.heightOffset = 4;
  11530. this.cameraAcceleration = 0.05;
  11531. this.maxCameraSpeed = 20;
  11532. this.target = target;
  11533. }
  11534. FollowCamera.prototype.getRadians = function (degrees) {
  11535. return degrees * Math.PI / 180;
  11536. };
  11537. FollowCamera.prototype.follow = function (cameraTarget) {
  11538. if (!cameraTarget)
  11539. return;
  11540. var yRotation;
  11541. if (cameraTarget.rotationQuaternion) {
  11542. var rotMatrix = new BABYLON.Matrix();
  11543. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11544. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11545. }
  11546. else {
  11547. yRotation = cameraTarget.rotation.y;
  11548. }
  11549. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11550. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11551. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11552. var dx = targetX - this.position.x;
  11553. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11554. var dz = (targetZ) - this.position.z;
  11555. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11556. var vy = dy * this.cameraAcceleration;
  11557. var vz = dz * this.cameraAcceleration * 2;
  11558. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11559. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11560. }
  11561. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11562. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11563. }
  11564. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11565. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11566. }
  11567. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11568. this.setTarget(cameraTarget.position);
  11569. };
  11570. FollowCamera.prototype._checkInputs = function () {
  11571. _super.prototype._checkInputs.call(this);
  11572. this.follow(this.target);
  11573. };
  11574. FollowCamera.prototype.getTypeName = function () {
  11575. return "FollowCamera";
  11576. };
  11577. __decorate([
  11578. BABYLON.serialize()
  11579. ], FollowCamera.prototype, "radius", void 0);
  11580. __decorate([
  11581. BABYLON.serialize()
  11582. ], FollowCamera.prototype, "rotationOffset", void 0);
  11583. __decorate([
  11584. BABYLON.serialize()
  11585. ], FollowCamera.prototype, "heightOffset", void 0);
  11586. __decorate([
  11587. BABYLON.serialize()
  11588. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  11589. __decorate([
  11590. BABYLON.serialize()
  11591. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  11592. __decorate([
  11593. BABYLON.serializeAsMeshReference("lockedTargetId")
  11594. ], FollowCamera.prototype, "target", void 0);
  11595. return FollowCamera;
  11596. })(BABYLON.TargetCamera);
  11597. BABYLON.FollowCamera = FollowCamera;
  11598. var ArcFollowCamera = (function (_super) {
  11599. __extends(ArcFollowCamera, _super);
  11600. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11601. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11602. this.alpha = alpha;
  11603. this.beta = beta;
  11604. this.radius = radius;
  11605. this.target = target;
  11606. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11607. this.follow();
  11608. }
  11609. ArcFollowCamera.prototype.follow = function () {
  11610. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11611. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11612. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11613. this.position = this.target.position.add(this._cartesianCoordinates);
  11614. this.setTarget(this.target.position);
  11615. };
  11616. ArcFollowCamera.prototype._checkInputs = function () {
  11617. _super.prototype._checkInputs.call(this);
  11618. this.follow();
  11619. };
  11620. ArcFollowCamera.prototype.getTypeName = function () {
  11621. return "ArcFollowCamera";
  11622. };
  11623. return ArcFollowCamera;
  11624. })(BABYLON.TargetCamera);
  11625. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11626. })(BABYLON || (BABYLON = {}));
  11627. var BABYLON;
  11628. (function (BABYLON) {
  11629. // We're mainly based on the logic defined into the FreeCamera code
  11630. var TouchCamera = (function (_super) {
  11631. __extends(TouchCamera, _super);
  11632. function TouchCamera(name, position, scene) {
  11633. _super.call(this, name, position, scene);
  11634. this._offsetX = null;
  11635. this._offsetY = null;
  11636. this._pointerCount = 0;
  11637. this._pointerPressed = [];
  11638. this.touchAngularSensibility = 200000.0;
  11639. this.touchMoveSensibility = 250.0;
  11640. }
  11641. TouchCamera.prototype._onLostFocus = function (e) {
  11642. this._offsetX = null;
  11643. this._offsetY = null;
  11644. _super.prototype._onLostFocus.call(this, e);
  11645. };
  11646. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11647. var _this = this;
  11648. var previousPosition;
  11649. if (this._attachedCanvas) {
  11650. return;
  11651. }
  11652. if (this._onPointerDown === undefined) {
  11653. this._onPointerDown = function (evt) {
  11654. if (evt.pointerType === "mouse") {
  11655. return;
  11656. }
  11657. if (!noPreventDefault) {
  11658. evt.preventDefault();
  11659. }
  11660. _this._pointerPressed.push(evt.pointerId);
  11661. if (_this._pointerPressed.length !== 1) {
  11662. return;
  11663. }
  11664. previousPosition = {
  11665. x: evt.clientX,
  11666. y: evt.clientY
  11667. };
  11668. };
  11669. this._onPointerUp = function (evt) {
  11670. if (evt.pointerType === "mouse") {
  11671. return;
  11672. }
  11673. if (!noPreventDefault) {
  11674. evt.preventDefault();
  11675. }
  11676. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11677. if (index === -1) {
  11678. return;
  11679. }
  11680. _this._pointerPressed.splice(index, 1);
  11681. if (index != 0) {
  11682. return;
  11683. }
  11684. previousPosition = null;
  11685. _this._offsetX = null;
  11686. _this._offsetY = null;
  11687. };
  11688. this._onPointerMove = function (evt) {
  11689. if (evt.pointerType === "mouse") {
  11690. return;
  11691. }
  11692. if (!noPreventDefault) {
  11693. evt.preventDefault();
  11694. }
  11695. if (!previousPosition) {
  11696. return;
  11697. }
  11698. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11699. if (index != 0) {
  11700. return;
  11701. }
  11702. _this._offsetX = evt.clientX - previousPosition.x;
  11703. _this._offsetY = -(evt.clientY - previousPosition.y);
  11704. };
  11705. }
  11706. canvas.addEventListener("pointerdown", this._onPointerDown);
  11707. canvas.addEventListener("pointerup", this._onPointerUp);
  11708. canvas.addEventListener("pointerout", this._onPointerUp);
  11709. canvas.addEventListener("pointermove", this._onPointerMove);
  11710. _super.prototype.attachControl.call(this, canvas);
  11711. };
  11712. TouchCamera.prototype.detachControl = function (canvas) {
  11713. if (this._attachedCanvas !== canvas) {
  11714. return;
  11715. }
  11716. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11717. canvas.removeEventListener("pointerup", this._onPointerUp);
  11718. canvas.removeEventListener("pointerout", this._onPointerUp);
  11719. canvas.removeEventListener("pointermove", this._onPointerMove);
  11720. _super.prototype.detachControl.call(this, canvas);
  11721. };
  11722. TouchCamera.prototype._checkInputs = function () {
  11723. if (this._offsetX) {
  11724. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11725. if (this._pointerPressed.length > 1) {
  11726. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11727. }
  11728. else {
  11729. var speed = this._computeLocalCameraSpeed();
  11730. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11731. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11732. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11733. }
  11734. }
  11735. _super.prototype._checkInputs.call(this);
  11736. };
  11737. TouchCamera.prototype.getTypeName = function () {
  11738. return "TouchCamera";
  11739. };
  11740. __decorate([
  11741. BABYLON.serialize()
  11742. ], TouchCamera.prototype, "touchAngularSensibility", void 0);
  11743. __decorate([
  11744. BABYLON.serialize()
  11745. ], TouchCamera.prototype, "touchMoveSensibility", void 0);
  11746. return TouchCamera;
  11747. })(BABYLON.FreeCamera);
  11748. BABYLON.TouchCamera = TouchCamera;
  11749. })(BABYLON || (BABYLON = {}));
  11750. var BABYLON;
  11751. (function (BABYLON) {
  11752. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11753. var ArcRotateCamera = (function (_super) {
  11754. __extends(ArcRotateCamera, _super);
  11755. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11756. var _this = this;
  11757. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11758. this.inertialAlphaOffset = 0;
  11759. this.inertialBetaOffset = 0;
  11760. this.inertialRadiusOffset = 0;
  11761. this.lowerAlphaLimit = null;
  11762. this.upperAlphaLimit = null;
  11763. this.lowerBetaLimit = 0.01;
  11764. this.upperBetaLimit = Math.PI;
  11765. this.lowerRadiusLimit = null;
  11766. this.upperRadiusLimit = null;
  11767. this.angularSensibilityX = 1000.0;
  11768. this.angularSensibilityY = 1000.0;
  11769. this.wheelPrecision = 3.0;
  11770. this.pinchPrecision = 2.0;
  11771. this.panningSensibility = 50.0;
  11772. this.inertialPanningX = 0;
  11773. this.inertialPanningY = 0;
  11774. this.keysUp = [38];
  11775. this.keysDown = [40];
  11776. this.keysLeft = [37];
  11777. this.keysRight = [39];
  11778. this.zoomOnFactor = 1;
  11779. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11780. this.pinchInwards = true;
  11781. this.allowUpsideDown = true;
  11782. this._keys = [];
  11783. this._viewMatrix = new BABYLON.Matrix();
  11784. // Panning
  11785. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11786. this._isRightClick = false;
  11787. this._isCtrlPushed = false;
  11788. this.checkCollisions = false;
  11789. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11790. this._collider = new BABYLON.Collider();
  11791. this._previousPosition = BABYLON.Vector3.Zero();
  11792. this._collisionVelocity = BABYLON.Vector3.Zero();
  11793. this._newPosition = BABYLON.Vector3.Zero();
  11794. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11795. if (collidedMesh === void 0) { collidedMesh = null; }
  11796. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11797. newPosition.multiplyInPlace(_this._collider.radius);
  11798. }
  11799. if (!collidedMesh) {
  11800. _this._previousPosition.copyFrom(_this.position);
  11801. }
  11802. else {
  11803. _this.setPosition(newPosition);
  11804. if (_this.onCollide) {
  11805. _this.onCollide(collidedMesh);
  11806. }
  11807. }
  11808. // Recompute because of constraints
  11809. var cosa = Math.cos(_this.alpha);
  11810. var sina = Math.sin(_this.alpha);
  11811. var cosb = Math.cos(_this.beta);
  11812. var sinb = Math.sin(_this.beta);
  11813. if (sinb === 0) {
  11814. sinb = 0.0001;
  11815. }
  11816. var target = _this._getTargetPosition();
  11817. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11818. _this.position.copyFrom(_this._newPosition);
  11819. var up = _this.upVector;
  11820. if (_this.allowUpsideDown && _this.beta < 0) {
  11821. up = up.clone();
  11822. up = up.negate();
  11823. }
  11824. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11825. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11826. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11827. _this._collisionTriggered = false;
  11828. };
  11829. if (!target) {
  11830. this.target = BABYLON.Vector3.Zero();
  11831. }
  11832. else {
  11833. this.target = target;
  11834. }
  11835. this.alpha = alpha;
  11836. this.beta = beta;
  11837. this.radius = radius;
  11838. this.getViewMatrix();
  11839. }
  11840. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11841. //deprecated angularSensibility support
  11842. get: function () {
  11843. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11844. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11845. },
  11846. //deprecated angularSensibility support
  11847. set: function (value) {
  11848. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11849. this.angularSensibilityX = value;
  11850. this.angularSensibilityY = value;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. // Cache
  11856. ArcRotateCamera.prototype._initCache = function () {
  11857. _super.prototype._initCache.call(this);
  11858. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11859. this._cache.alpha = undefined;
  11860. this._cache.beta = undefined;
  11861. this._cache.radius = undefined;
  11862. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11863. };
  11864. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11865. if (!ignoreParentClass) {
  11866. _super.prototype._updateCache.call(this);
  11867. }
  11868. this._cache.target.copyFrom(this._getTargetPosition());
  11869. this._cache.alpha = this.alpha;
  11870. this._cache.beta = this.beta;
  11871. this._cache.radius = this.radius;
  11872. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11873. };
  11874. ArcRotateCamera.prototype._getTargetPosition = function () {
  11875. if (this.target.getAbsolutePosition) {
  11876. return this.target.getAbsolutePosition();
  11877. }
  11878. return this.target;
  11879. };
  11880. // Synchronized
  11881. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11882. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11883. return false;
  11884. return this._cache.target.equals(this.target)
  11885. && this._cache.alpha === this.alpha
  11886. && this._cache.beta === this.beta
  11887. && this._cache.radius === this.radius
  11888. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11889. };
  11890. // Methods
  11891. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11892. var _this = this;
  11893. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11894. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11895. var previousPinchDistance = 0;
  11896. var pointers = new BABYLON.SmartCollection();
  11897. if (this._attachedElement) {
  11898. return;
  11899. }
  11900. this._attachedElement = element;
  11901. var engine = this.getEngine();
  11902. if (this._onPointerDown === undefined) {
  11903. this._onPointerDown = function (evt) {
  11904. // Manage panning with right click
  11905. _this._isRightClick = evt.button === 2;
  11906. // manage pointers
  11907. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11908. cacheSoloPointer = pointers.item(evt.pointerId);
  11909. if (!noPreventDefault) {
  11910. evt.preventDefault();
  11911. }
  11912. };
  11913. this._onPointerUp = function (evt) {
  11914. cacheSoloPointer = null;
  11915. previousPinchDistance = 0;
  11916. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11917. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11918. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11919. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11920. pointers.empty();
  11921. if (!noPreventDefault) {
  11922. evt.preventDefault();
  11923. }
  11924. };
  11925. this._onContextMenu = function (evt) {
  11926. evt.preventDefault();
  11927. };
  11928. this._onPointerMove = function (evt) {
  11929. if (!noPreventDefault) {
  11930. evt.preventDefault();
  11931. }
  11932. switch (pointers.count) {
  11933. case 1:
  11934. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11935. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11936. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11937. }
  11938. else {
  11939. var offsetX = evt.clientX - cacheSoloPointer.x;
  11940. var offsetY = evt.clientY - cacheSoloPointer.y;
  11941. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11942. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11943. }
  11944. cacheSoloPointer.x = evt.clientX;
  11945. cacheSoloPointer.y = evt.clientY;
  11946. break;
  11947. case 2:
  11948. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11949. pointers.item(evt.pointerId).x = evt.clientX;
  11950. pointers.item(evt.pointerId).y = evt.clientY;
  11951. var direction = _this.pinchInwards ? 1 : -1;
  11952. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11953. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11954. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11955. if (previousPinchDistance === 0) {
  11956. previousPinchDistance = pinchSquaredDistance;
  11957. return;
  11958. }
  11959. if (pinchSquaredDistance !== previousPinchDistance) {
  11960. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11961. previousPinchDistance = pinchSquaredDistance;
  11962. }
  11963. break;
  11964. default:
  11965. if (pointers.item(evt.pointerId)) {
  11966. pointers.item(evt.pointerId).x = evt.clientX;
  11967. pointers.item(evt.pointerId).y = evt.clientY;
  11968. }
  11969. }
  11970. };
  11971. this._onMouseMove = function (evt) {
  11972. if (!engine.isPointerLock) {
  11973. return;
  11974. }
  11975. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11976. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11977. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11978. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11979. if (!noPreventDefault) {
  11980. evt.preventDefault();
  11981. }
  11982. };
  11983. this._wheel = function (event) {
  11984. var delta = 0;
  11985. if (event.wheelDelta) {
  11986. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11987. }
  11988. else if (event.detail) {
  11989. delta = -event.detail / _this.wheelPrecision;
  11990. }
  11991. if (delta)
  11992. _this.inertialRadiusOffset += delta;
  11993. if (event.preventDefault) {
  11994. if (!noPreventDefault) {
  11995. event.preventDefault();
  11996. }
  11997. }
  11998. };
  11999. this._onKeyDown = function (evt) {
  12000. _this._isCtrlPushed = evt.ctrlKey;
  12001. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12002. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12003. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12004. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12005. var index = _this._keys.indexOf(evt.keyCode);
  12006. if (index === -1) {
  12007. _this._keys.push(evt.keyCode);
  12008. }
  12009. if (evt.preventDefault) {
  12010. if (!noPreventDefault) {
  12011. evt.preventDefault();
  12012. }
  12013. }
  12014. }
  12015. };
  12016. this._onKeyUp = function (evt) {
  12017. _this._isCtrlPushed = evt.ctrlKey;
  12018. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12019. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12020. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12021. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12022. var index = _this._keys.indexOf(evt.keyCode);
  12023. if (index >= 0) {
  12024. _this._keys.splice(index, 1);
  12025. }
  12026. if (evt.preventDefault) {
  12027. if (!noPreventDefault) {
  12028. evt.preventDefault();
  12029. }
  12030. }
  12031. }
  12032. };
  12033. this._onLostFocus = function () {
  12034. _this._keys = [];
  12035. pointers.empty();
  12036. previousPinchDistance = 0;
  12037. cacheSoloPointer = null;
  12038. };
  12039. this._onGestureStart = function (e) {
  12040. if (window.MSGesture === undefined) {
  12041. return;
  12042. }
  12043. if (!_this._MSGestureHandler) {
  12044. _this._MSGestureHandler = new MSGesture();
  12045. _this._MSGestureHandler.target = element;
  12046. }
  12047. _this._MSGestureHandler.addPointer(e.pointerId);
  12048. };
  12049. this._onGesture = function (e) {
  12050. _this.radius *= e.scale;
  12051. if (e.preventDefault) {
  12052. if (!noPreventDefault) {
  12053. e.stopPropagation();
  12054. e.preventDefault();
  12055. }
  12056. }
  12057. };
  12058. this._reset = function () {
  12059. _this._keys = [];
  12060. _this.inertialAlphaOffset = 0;
  12061. _this.inertialBetaOffset = 0;
  12062. _this.inertialRadiusOffset = 0;
  12063. pointers.empty();
  12064. previousPinchDistance = 0;
  12065. cacheSoloPointer = null;
  12066. };
  12067. }
  12068. if (!useCtrlForPanning) {
  12069. element.addEventListener("contextmenu", this._onContextMenu, false);
  12070. }
  12071. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12072. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12073. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12074. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12075. element.addEventListener("mousemove", this._onMouseMove, false);
  12076. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12077. element.addEventListener("MSGestureChange", this._onGesture, false);
  12078. element.addEventListener('mousewheel', this._wheel, false);
  12079. element.addEventListener('DOMMouseScroll', this._wheel, false);
  12080. BABYLON.Tools.RegisterTopRootEvents([
  12081. { name: "keydown", handler: this._onKeyDown },
  12082. { name: "keyup", handler: this._onKeyUp },
  12083. { name: "blur", handler: this._onLostFocus }
  12084. ]);
  12085. };
  12086. ArcRotateCamera.prototype.detachControl = function (element) {
  12087. if (this._attachedElement !== element) {
  12088. return;
  12089. }
  12090. element.removeEventListener("contextmenu", this._onContextMenu);
  12091. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12092. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12093. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12094. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12095. element.removeEventListener("mousemove", this._onMouseMove);
  12096. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12097. element.removeEventListener("MSGestureChange", this._onGesture);
  12098. element.removeEventListener('mousewheel', this._wheel);
  12099. element.removeEventListener('DOMMouseScroll', this._wheel);
  12100. BABYLON.Tools.UnregisterTopRootEvents([
  12101. { name: "keydown", handler: this._onKeyDown },
  12102. { name: "keyup", handler: this._onKeyUp },
  12103. { name: "blur", handler: this._onLostFocus }
  12104. ]);
  12105. this._MSGestureHandler = null;
  12106. this._attachedElement = null;
  12107. if (this._reset) {
  12108. this._reset();
  12109. }
  12110. };
  12111. ArcRotateCamera.prototype._checkInputs = function () {
  12112. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  12113. if (this._collisionTriggered) {
  12114. return;
  12115. }
  12116. // Keyboard
  12117. for (var index = 0; index < this._keys.length; index++) {
  12118. var keyCode = this._keys[index];
  12119. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12120. this.inertialAlphaOffset -= 0.01;
  12121. }
  12122. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12123. this.inertialBetaOffset -= 0.01;
  12124. }
  12125. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12126. this.inertialAlphaOffset += 0.01;
  12127. }
  12128. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12129. this.inertialBetaOffset += 0.01;
  12130. }
  12131. }
  12132. // Inertia
  12133. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  12134. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  12135. this.beta += this.inertialBetaOffset;
  12136. this.radius -= this.inertialRadiusOffset;
  12137. this.inertialAlphaOffset *= this.inertia;
  12138. this.inertialBetaOffset *= this.inertia;
  12139. this.inertialRadiusOffset *= this.inertia;
  12140. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  12141. this.inertialAlphaOffset = 0;
  12142. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  12143. this.inertialBetaOffset = 0;
  12144. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  12145. this.inertialRadiusOffset = 0;
  12146. }
  12147. // Panning inertia
  12148. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  12149. if (!this._localDirection) {
  12150. this._localDirection = BABYLON.Vector3.Zero();
  12151. this._transformedDirection = BABYLON.Vector3.Zero();
  12152. }
  12153. this.inertialPanningX *= this.inertia;
  12154. this.inertialPanningY *= this.inertia;
  12155. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  12156. this.inertialPanningX = 0;
  12157. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  12158. this.inertialPanningY = 0;
  12159. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  12160. this._localDirection.multiplyInPlace(this.panningAxis);
  12161. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  12162. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  12163. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  12164. if (!this.panningAxis.y) {
  12165. this._transformedDirection.y = 0;
  12166. }
  12167. this.target.addInPlace(this._transformedDirection);
  12168. }
  12169. // Limits
  12170. this._checkLimits();
  12171. _super.prototype._checkInputs.call(this);
  12172. };
  12173. ArcRotateCamera.prototype._checkLimits = function () {
  12174. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  12175. if (this.allowUpsideDown && this.beta > Math.PI) {
  12176. this.beta = this.beta - (2 * Math.PI);
  12177. }
  12178. }
  12179. else {
  12180. if (this.beta < this.lowerBetaLimit) {
  12181. this.beta = this.lowerBetaLimit;
  12182. }
  12183. }
  12184. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  12185. if (this.allowUpsideDown && this.beta < -Math.PI) {
  12186. this.beta = this.beta + (2 * Math.PI);
  12187. }
  12188. }
  12189. else {
  12190. if (this.beta > this.upperBetaLimit) {
  12191. this.beta = this.upperBetaLimit;
  12192. }
  12193. }
  12194. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  12195. this.alpha = this.lowerAlphaLimit;
  12196. }
  12197. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  12198. this.alpha = this.upperAlphaLimit;
  12199. }
  12200. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  12201. this.radius = this.lowerRadiusLimit;
  12202. }
  12203. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  12204. this.radius = this.upperRadiusLimit;
  12205. }
  12206. };
  12207. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  12208. var radiusv3 = this.position.subtract(this._getTargetPosition());
  12209. this.radius = radiusv3.length();
  12210. // Alpha
  12211. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  12212. if (radiusv3.z < 0) {
  12213. this.alpha = 2 * Math.PI - this.alpha;
  12214. }
  12215. // Beta
  12216. this.beta = Math.acos(radiusv3.y / this.radius);
  12217. this._checkLimits();
  12218. };
  12219. ArcRotateCamera.prototype.setPosition = function (position) {
  12220. if (this.position.equals(position)) {
  12221. return;
  12222. }
  12223. this.position = position;
  12224. this.rebuildAnglesAndRadius();
  12225. };
  12226. ArcRotateCamera.prototype.setTarget = function (target) {
  12227. if (this._getTargetPosition().equals(target)) {
  12228. return;
  12229. }
  12230. this.target = target;
  12231. this.rebuildAnglesAndRadius();
  12232. };
  12233. ArcRotateCamera.prototype._getViewMatrix = function () {
  12234. // Compute
  12235. var cosa = Math.cos(this.alpha);
  12236. var sina = Math.sin(this.alpha);
  12237. var cosb = Math.cos(this.beta);
  12238. var sinb = Math.sin(this.beta);
  12239. if (sinb === 0) {
  12240. sinb = 0.0001;
  12241. }
  12242. var target = this._getTargetPosition();
  12243. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  12244. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  12245. this._collider.radius = this.collisionRadius;
  12246. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  12247. this._collisionTriggered = true;
  12248. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12249. }
  12250. else {
  12251. this.position.copyFrom(this._newPosition);
  12252. var up = this.upVector;
  12253. if (this.allowUpsideDown && this.beta < 0) {
  12254. up = up.clone();
  12255. up = up.negate();
  12256. }
  12257. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  12258. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  12259. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  12260. }
  12261. return this._viewMatrix;
  12262. };
  12263. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  12264. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12265. meshes = meshes || this.getScene().meshes;
  12266. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  12267. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  12268. this.radius = distance * this.zoomOnFactor;
  12269. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  12270. };
  12271. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  12272. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12273. var meshesOrMinMaxVector;
  12274. var distance;
  12275. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  12276. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  12277. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  12278. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  12279. }
  12280. else {
  12281. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  12282. distance = meshesOrMinMaxVectorAndDistance.distance;
  12283. }
  12284. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  12285. if (!doNotUpdateMaxZ) {
  12286. this.maxZ = distance * 2;
  12287. }
  12288. };
  12289. /**
  12290. * @override
  12291. * Override Camera.createRigCamera
  12292. */
  12293. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12294. switch (this.cameraRigMode) {
  12295. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12296. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12297. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12298. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12299. case BABYLON.Camera.RIG_MODE_VR:
  12300. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12301. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12302. }
  12303. return null;
  12304. };
  12305. /**
  12306. * @override
  12307. * Override Camera._updateRigCameras
  12308. */
  12309. ArcRotateCamera.prototype._updateRigCameras = function () {
  12310. switch (this.cameraRigMode) {
  12311. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12312. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12313. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12314. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12315. case BABYLON.Camera.RIG_MODE_VR:
  12316. var camLeft = this._rigCameras[0];
  12317. var camRight = this._rigCameras[1];
  12318. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12319. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12320. camLeft.beta = camRight.beta = this.beta;
  12321. camLeft.radius = camRight.radius = this.radius;
  12322. break;
  12323. }
  12324. _super.prototype._updateRigCameras.call(this);
  12325. };
  12326. ArcRotateCamera.prototype.getTypeName = function () {
  12327. return "ArcRotateCamera";
  12328. };
  12329. __decorate([
  12330. BABYLON.serialize()
  12331. ], ArcRotateCamera.prototype, "alpha", void 0);
  12332. __decorate([
  12333. BABYLON.serialize()
  12334. ], ArcRotateCamera.prototype, "beta", void 0);
  12335. __decorate([
  12336. BABYLON.serialize()
  12337. ], ArcRotateCamera.prototype, "radius", void 0);
  12338. __decorate([
  12339. BABYLON.serializeAsVector3()
  12340. ], ArcRotateCamera.prototype, "target", void 0);
  12341. __decorate([
  12342. BABYLON.serialize()
  12343. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  12344. __decorate([
  12345. BABYLON.serialize()
  12346. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  12347. __decorate([
  12348. BABYLON.serialize()
  12349. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  12350. __decorate([
  12351. BABYLON.serialize()
  12352. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  12353. __decorate([
  12354. BABYLON.serialize()
  12355. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  12356. __decorate([
  12357. BABYLON.serialize()
  12358. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  12359. __decorate([
  12360. BABYLON.serialize()
  12361. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  12362. __decorate([
  12363. BABYLON.serialize()
  12364. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  12365. __decorate([
  12366. BABYLON.serialize()
  12367. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  12368. __decorate([
  12369. BABYLON.serialize()
  12370. ], ArcRotateCamera.prototype, "angularSensibilityX", void 0);
  12371. __decorate([
  12372. BABYLON.serialize()
  12373. ], ArcRotateCamera.prototype, "angularSensibilityY", void 0);
  12374. __decorate([
  12375. BABYLON.serialize()
  12376. ], ArcRotateCamera.prototype, "wheelPrecision", void 0);
  12377. __decorate([
  12378. BABYLON.serialize()
  12379. ], ArcRotateCamera.prototype, "pinchPrecision", void 0);
  12380. __decorate([
  12381. BABYLON.serialize()
  12382. ], ArcRotateCamera.prototype, "panningSensibility", void 0);
  12383. __decorate([
  12384. BABYLON.serialize()
  12385. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  12386. __decorate([
  12387. BABYLON.serialize()
  12388. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  12389. __decorate([
  12390. BABYLON.serialize()
  12391. ], ArcRotateCamera.prototype, "keysUp", void 0);
  12392. __decorate([
  12393. BABYLON.serialize()
  12394. ], ArcRotateCamera.prototype, "keysDown", void 0);
  12395. __decorate([
  12396. BABYLON.serialize()
  12397. ], ArcRotateCamera.prototype, "keysLeft", void 0);
  12398. __decorate([
  12399. BABYLON.serialize()
  12400. ], ArcRotateCamera.prototype, "keysRight", void 0);
  12401. __decorate([
  12402. BABYLON.serialize()
  12403. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  12404. __decorate([
  12405. BABYLON.serialize()
  12406. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  12407. return ArcRotateCamera;
  12408. })(BABYLON.TargetCamera);
  12409. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12410. })(BABYLON || (BABYLON = {}));
  12411. var BABYLON;
  12412. (function (BABYLON) {
  12413. var RenderingManager = (function () {
  12414. function RenderingManager(scene) {
  12415. this._renderingGroups = new Array();
  12416. this._scene = scene;
  12417. }
  12418. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12419. if (this._scene._activeParticleSystems.length === 0) {
  12420. return;
  12421. }
  12422. // Particles
  12423. var activeCamera = this._scene.activeCamera;
  12424. var beforeParticlesDate = BABYLON.Tools.Now;
  12425. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12426. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12427. if (particleSystem.renderingGroupId !== index) {
  12428. continue;
  12429. }
  12430. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12431. continue;
  12432. }
  12433. this._clearDepthBuffer();
  12434. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12435. this._scene._activeParticles += particleSystem.render();
  12436. }
  12437. }
  12438. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12439. };
  12440. RenderingManager.prototype._renderSprites = function (index) {
  12441. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12442. return;
  12443. }
  12444. // Sprites
  12445. var activeCamera = this._scene.activeCamera;
  12446. var beforeSpritessDate = BABYLON.Tools.Now;
  12447. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12448. var spriteManager = this._scene.spriteManagers[id];
  12449. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12450. this._clearDepthBuffer();
  12451. spriteManager.render();
  12452. }
  12453. }
  12454. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12455. };
  12456. RenderingManager.prototype._clearDepthBuffer = function () {
  12457. if (this._depthBufferAlreadyCleaned) {
  12458. return;
  12459. }
  12460. this._scene.getEngine().clear(0, false, true);
  12461. this._depthBufferAlreadyCleaned = true;
  12462. };
  12463. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12464. if (this._currentRenderSprites) {
  12465. this._renderSprites(this._currentIndex);
  12466. }
  12467. if (this._currentRenderParticles) {
  12468. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12469. }
  12470. };
  12471. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12472. this._currentActiveMeshes = activeMeshes;
  12473. this._currentRenderParticles = renderParticles;
  12474. this._currentRenderSprites = renderSprites;
  12475. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12476. this._depthBufferAlreadyCleaned = index == 0;
  12477. var renderingGroup = this._renderingGroups[index];
  12478. var needToStepBack = false;
  12479. this._currentIndex = index;
  12480. if (renderingGroup) {
  12481. this._clearDepthBuffer();
  12482. if (!renderingGroup.onBeforeTransparentRendering) {
  12483. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12484. }
  12485. if (!renderingGroup.render(customRenderFunction)) {
  12486. this._renderingGroups.splice(index, 1);
  12487. needToStepBack = true;
  12488. this._renderSpritesAndParticles();
  12489. }
  12490. }
  12491. else {
  12492. this._renderSpritesAndParticles();
  12493. }
  12494. if (needToStepBack) {
  12495. index--;
  12496. }
  12497. }
  12498. };
  12499. RenderingManager.prototype.reset = function () {
  12500. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12501. if (renderingGroup) {
  12502. renderingGroup.prepare();
  12503. }
  12504. });
  12505. };
  12506. RenderingManager.prototype.dispatch = function (subMesh) {
  12507. var mesh = subMesh.getMesh();
  12508. var renderingGroupId = mesh.renderingGroupId || 0;
  12509. if (!this._renderingGroups[renderingGroupId]) {
  12510. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12511. }
  12512. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12513. };
  12514. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12515. return RenderingManager;
  12516. })();
  12517. BABYLON.RenderingManager = RenderingManager;
  12518. })(BABYLON || (BABYLON = {}));
  12519. var BABYLON;
  12520. (function (BABYLON) {
  12521. var RenderingGroup = (function () {
  12522. function RenderingGroup(index, scene) {
  12523. this.index = index;
  12524. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12525. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12526. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12527. this._scene = scene;
  12528. }
  12529. RenderingGroup.prototype.render = function (customRenderFunction) {
  12530. if (customRenderFunction) {
  12531. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12532. return true;
  12533. }
  12534. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12535. if (this.onBeforeTransparentRendering) {
  12536. this.onBeforeTransparentRendering();
  12537. }
  12538. return false;
  12539. }
  12540. var engine = this._scene.getEngine();
  12541. // Opaque
  12542. var subIndex;
  12543. var submesh;
  12544. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12545. submesh = this._opaqueSubMeshes.data[subIndex];
  12546. submesh.render(false);
  12547. }
  12548. // Alpha test
  12549. engine.setAlphaTesting(true);
  12550. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12551. submesh = this._alphaTestSubMeshes.data[subIndex];
  12552. submesh.render(false);
  12553. }
  12554. engine.setAlphaTesting(false);
  12555. if (this.onBeforeTransparentRendering) {
  12556. this.onBeforeTransparentRendering();
  12557. }
  12558. // Transparent
  12559. if (this._transparentSubMeshes.length) {
  12560. // Sorting
  12561. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12562. submesh = this._transparentSubMeshes.data[subIndex];
  12563. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12564. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12565. }
  12566. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12567. sortedArray.sort(function (a, b) {
  12568. // Alpha index first
  12569. if (a._alphaIndex > b._alphaIndex) {
  12570. return 1;
  12571. }
  12572. if (a._alphaIndex < b._alphaIndex) {
  12573. return -1;
  12574. }
  12575. // Then distance to camera
  12576. if (a._distanceToCamera < b._distanceToCamera) {
  12577. return 1;
  12578. }
  12579. if (a._distanceToCamera > b._distanceToCamera) {
  12580. return -1;
  12581. }
  12582. return 0;
  12583. });
  12584. // Rendering
  12585. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12586. submesh = sortedArray[subIndex];
  12587. submesh.render(true);
  12588. }
  12589. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12590. }
  12591. return true;
  12592. };
  12593. RenderingGroup.prototype.prepare = function () {
  12594. this._opaqueSubMeshes.reset();
  12595. this._transparentSubMeshes.reset();
  12596. this._alphaTestSubMeshes.reset();
  12597. };
  12598. RenderingGroup.prototype.dispatch = function (subMesh) {
  12599. var material = subMesh.getMaterial();
  12600. var mesh = subMesh.getMesh();
  12601. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12602. this._transparentSubMeshes.push(subMesh);
  12603. }
  12604. else if (material.needAlphaTesting()) {
  12605. this._alphaTestSubMeshes.push(subMesh);
  12606. }
  12607. else {
  12608. this._opaqueSubMeshes.push(subMesh); // Opaque
  12609. }
  12610. };
  12611. return RenderingGroup;
  12612. })();
  12613. BABYLON.RenderingGroup = RenderingGroup;
  12614. })(BABYLON || (BABYLON = {}));
  12615. var BABYLON;
  12616. (function (BABYLON) {
  12617. /**
  12618. * Represents a scene to be rendered by the engine.
  12619. * @see http://doc.babylonjs.com/page.php?p=21911
  12620. */
  12621. var Scene = (function () {
  12622. /**
  12623. * @constructor
  12624. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12625. */
  12626. function Scene(engine) {
  12627. // Members
  12628. this.autoClear = true;
  12629. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12630. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12631. this.forceWireframe = false;
  12632. this.forcePointsCloud = false;
  12633. this.forceShowBoundingBoxes = false;
  12634. this.animationsEnabled = true;
  12635. this.constantlyUpdateMeshUnderPointer = false;
  12636. // Animations
  12637. this.animations = [];
  12638. 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
  12639. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12640. this._startingPointerTime = 0;
  12641. // Fog
  12642. /**
  12643. * is fog enabled on this scene.
  12644. * @type {boolean}
  12645. */
  12646. this.fogEnabled = true;
  12647. this.fogMode = Scene.FOGMODE_NONE;
  12648. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12649. this.fogDensity = 0.1;
  12650. this.fogStart = 0;
  12651. this.fogEnd = 1000.0;
  12652. // Lights
  12653. /**
  12654. * is shadow enabled on this scene.
  12655. * @type {boolean}
  12656. */
  12657. this.shadowsEnabled = true;
  12658. /**
  12659. * is light enabled on this scene.
  12660. * @type {boolean}
  12661. */
  12662. this.lightsEnabled = true;
  12663. /**
  12664. * All of the lights added to this scene.
  12665. * @see BABYLON.Light
  12666. * @type {BABYLON.Light[]}
  12667. */
  12668. this.lights = new Array();
  12669. // Cameras
  12670. /**
  12671. * All of the cameras added to this scene.
  12672. * @see BABYLON.Camera
  12673. * @type {BABYLON.Camera[]}
  12674. */
  12675. this.cameras = new Array();
  12676. this.activeCameras = new Array();
  12677. // Meshes
  12678. /**
  12679. * All of the (abstract) meshes added to this scene.
  12680. * @see BABYLON.AbstractMesh
  12681. * @type {BABYLON.AbstractMesh[]}
  12682. */
  12683. this.meshes = new Array();
  12684. // Geometries
  12685. this._geometries = new Array();
  12686. this.materials = new Array();
  12687. this.multiMaterials = new Array();
  12688. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12689. // Textures
  12690. this.texturesEnabled = true;
  12691. this.textures = new Array();
  12692. // Particles
  12693. this.particlesEnabled = true;
  12694. this.particleSystems = new Array();
  12695. // Sprites
  12696. this.spritesEnabled = true;
  12697. this.spriteManagers = new Array();
  12698. // Layers
  12699. this.layers = new Array();
  12700. // Skeletons
  12701. this.skeletonsEnabled = true;
  12702. this.skeletons = new Array();
  12703. // Lens flares
  12704. this.lensFlaresEnabled = true;
  12705. this.lensFlareSystems = new Array();
  12706. // Collisions
  12707. this.collisionsEnabled = true;
  12708. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12709. // Postprocesses
  12710. this.postProcessesEnabled = true;
  12711. // Customs render targets
  12712. this.renderTargetsEnabled = true;
  12713. this.dumpNextRenderTargets = false;
  12714. this.customRenderTargets = new Array();
  12715. // Imported meshes
  12716. this.importedMeshesFiles = new Array();
  12717. // Probes
  12718. this.probesEnabled = true;
  12719. this.reflectionProbes = new Array();
  12720. this._actionManagers = new Array();
  12721. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12722. // Procedural textures
  12723. this.proceduralTexturesEnabled = true;
  12724. this._proceduralTextures = new Array();
  12725. this.soundTracks = new Array();
  12726. this._audioEnabled = true;
  12727. this._headphone = false;
  12728. this._totalVertices = 0;
  12729. this._activeIndices = 0;
  12730. this._activeParticles = 0;
  12731. this._lastFrameDuration = 0;
  12732. this._evaluateActiveMeshesDuration = 0;
  12733. this._renderTargetsDuration = 0;
  12734. this._particlesDuration = 0;
  12735. this._renderDuration = 0;
  12736. this._spritesDuration = 0;
  12737. this._animationRatio = 0;
  12738. this._renderId = 0;
  12739. this._executeWhenReadyTimeoutId = -1;
  12740. this._toBeDisposed = new BABYLON.SmartArray(256);
  12741. this._onReadyCallbacks = new Array();
  12742. this._pendingData = []; //ANY
  12743. this._onBeforeRenderCallbacks = new Array();
  12744. this._onAfterRenderCallbacks = new Array();
  12745. this._activeMeshes = new BABYLON.SmartArray(256);
  12746. this._processedMaterials = new BABYLON.SmartArray(256);
  12747. this._renderTargets = new BABYLON.SmartArray(256);
  12748. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12749. this._activeSkeletons = new BABYLON.SmartArray(32);
  12750. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12751. this._activeBones = 0;
  12752. this._activeAnimatables = new Array();
  12753. this._transformMatrix = BABYLON.Matrix.Zero();
  12754. this._edgesRenderers = new BABYLON.SmartArray(16);
  12755. this._uniqueIdCounter = 0;
  12756. this._engine = engine;
  12757. engine.scenes.push(this);
  12758. this._renderingManager = new BABYLON.RenderingManager(this);
  12759. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12760. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12761. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12762. if (BABYLON.OutlineRenderer) {
  12763. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12764. }
  12765. this.attachControl();
  12766. this._debugLayer = new BABYLON.DebugLayer(this);
  12767. if (BABYLON.SoundTrack) {
  12768. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12769. }
  12770. //simplification queue
  12771. if (BABYLON.SimplificationQueue) {
  12772. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12773. }
  12774. //collision coordinator initialization. For now legacy per default.
  12775. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12776. }
  12777. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12778. get: function () {
  12779. return Scene._FOGMODE_NONE;
  12780. },
  12781. enumerable: true,
  12782. configurable: true
  12783. });
  12784. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12785. get: function () {
  12786. return Scene._FOGMODE_EXP;
  12787. },
  12788. enumerable: true,
  12789. configurable: true
  12790. });
  12791. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12792. get: function () {
  12793. return Scene._FOGMODE_EXP2;
  12794. },
  12795. enumerable: true,
  12796. configurable: true
  12797. });
  12798. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12799. get: function () {
  12800. return Scene._FOGMODE_LINEAR;
  12801. },
  12802. enumerable: true,
  12803. configurable: true
  12804. });
  12805. Object.defineProperty(Scene.prototype, "debugLayer", {
  12806. // Properties
  12807. get: function () {
  12808. return this._debugLayer;
  12809. },
  12810. enumerable: true,
  12811. configurable: true
  12812. });
  12813. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12814. get: function () {
  12815. return this._workerCollisions;
  12816. },
  12817. set: function (enabled) {
  12818. enabled = (enabled && !!Worker);
  12819. this._workerCollisions = enabled;
  12820. if (this.collisionCoordinator) {
  12821. this.collisionCoordinator.destroy();
  12822. }
  12823. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12824. this.collisionCoordinator.init(this);
  12825. },
  12826. enumerable: true,
  12827. configurable: true
  12828. });
  12829. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12830. get: function () {
  12831. return this._selectionOctree;
  12832. },
  12833. enumerable: true,
  12834. configurable: true
  12835. });
  12836. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12837. /**
  12838. * The mesh that is currently under the pointer.
  12839. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12840. */
  12841. get: function () {
  12842. return this._pointerOverMesh;
  12843. },
  12844. enumerable: true,
  12845. configurable: true
  12846. });
  12847. Object.defineProperty(Scene.prototype, "pointerX", {
  12848. /**
  12849. * Current on-screen X position of the pointer
  12850. * @return {number} X position of the pointer
  12851. */
  12852. get: function () {
  12853. return this._pointerX;
  12854. },
  12855. enumerable: true,
  12856. configurable: true
  12857. });
  12858. Object.defineProperty(Scene.prototype, "pointerY", {
  12859. /**
  12860. * Current on-screen Y position of the pointer
  12861. * @return {number} Y position of the pointer
  12862. */
  12863. get: function () {
  12864. return this._pointerY;
  12865. },
  12866. enumerable: true,
  12867. configurable: true
  12868. });
  12869. Scene.prototype.getCachedMaterial = function () {
  12870. return this._cachedMaterial;
  12871. };
  12872. Scene.prototype.getBoundingBoxRenderer = function () {
  12873. return this._boundingBoxRenderer;
  12874. };
  12875. Scene.prototype.getOutlineRenderer = function () {
  12876. return this._outlineRenderer;
  12877. };
  12878. Scene.prototype.getEngine = function () {
  12879. return this._engine;
  12880. };
  12881. Scene.prototype.getTotalVertices = function () {
  12882. return this._totalVertices;
  12883. };
  12884. Scene.prototype.getActiveIndices = function () {
  12885. return this._activeIndices;
  12886. };
  12887. Scene.prototype.getActiveParticles = function () {
  12888. return this._activeParticles;
  12889. };
  12890. Scene.prototype.getActiveBones = function () {
  12891. return this._activeBones;
  12892. };
  12893. // Stats
  12894. Scene.prototype.getLastFrameDuration = function () {
  12895. return this._lastFrameDuration;
  12896. };
  12897. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12898. return this._evaluateActiveMeshesDuration;
  12899. };
  12900. Scene.prototype.getActiveMeshes = function () {
  12901. return this._activeMeshes;
  12902. };
  12903. Scene.prototype.getRenderTargetsDuration = function () {
  12904. return this._renderTargetsDuration;
  12905. };
  12906. Scene.prototype.getRenderDuration = function () {
  12907. return this._renderDuration;
  12908. };
  12909. Scene.prototype.getParticlesDuration = function () {
  12910. return this._particlesDuration;
  12911. };
  12912. Scene.prototype.getSpritesDuration = function () {
  12913. return this._spritesDuration;
  12914. };
  12915. Scene.prototype.getAnimationRatio = function () {
  12916. return this._animationRatio;
  12917. };
  12918. Scene.prototype.getRenderId = function () {
  12919. return this._renderId;
  12920. };
  12921. Scene.prototype.incrementRenderId = function () {
  12922. this._renderId++;
  12923. };
  12924. Scene.prototype._updatePointerPosition = function (evt) {
  12925. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12926. this._pointerX = evt.clientX - canvasRect.left;
  12927. this._pointerY = evt.clientY - canvasRect.top;
  12928. this._unTranslatedPointerX = this._pointerX;
  12929. this._unTranslatedPointerY = this._pointerY;
  12930. if (this.cameraToUseForPointers) {
  12931. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12932. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12933. }
  12934. };
  12935. // Pointers handling
  12936. Scene.prototype.attachControl = function () {
  12937. var _this = this;
  12938. var spritePredicate = function (sprite) {
  12939. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12940. };
  12941. this._onPointerMove = function (evt) {
  12942. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12943. return;
  12944. }
  12945. var canvas = _this._engine.getRenderingCanvas();
  12946. _this._updatePointerPosition(evt);
  12947. if (!_this.pointerMovePredicate) {
  12948. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  12949. }
  12950. // Meshes
  12951. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  12952. if (pickResult.hit && pickResult.pickedMesh) {
  12953. _this.setPointerOverSprite(null);
  12954. _this.setPointerOverMesh(pickResult.pickedMesh);
  12955. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12956. canvas.style.cursor = "pointer";
  12957. }
  12958. else {
  12959. canvas.style.cursor = "";
  12960. }
  12961. }
  12962. else {
  12963. _this.setPointerOverMesh(null);
  12964. // Sprites
  12965. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12966. if (pickResult.hit && pickResult.pickedSprite) {
  12967. canvas.style.cursor = "pointer";
  12968. _this.setPointerOverSprite(pickResult.pickedSprite);
  12969. }
  12970. else {
  12971. _this.setPointerOverSprite(null);
  12972. // Restore pointer
  12973. canvas.style.cursor = "";
  12974. }
  12975. }
  12976. if (_this.onPointerMove) {
  12977. _this.onPointerMove(evt, pickResult);
  12978. }
  12979. };
  12980. this._onPointerDown = function (evt) {
  12981. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12982. return;
  12983. }
  12984. _this._updatePointerPosition(evt);
  12985. _this._startingPointerPosition.x = _this._pointerX;
  12986. _this._startingPointerPosition.y = _this._pointerY;
  12987. _this._startingPointerTime = new Date().getTime();
  12988. if (!_this.pointerDownPredicate) {
  12989. _this.pointerDownPredicate = function (mesh) {
  12990. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12991. };
  12992. }
  12993. // Meshes
  12994. _this._pickedDownMesh = null;
  12995. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  12996. if (pickResult.hit && pickResult.pickedMesh) {
  12997. if (pickResult.pickedMesh.actionManager) {
  12998. _this._pickedDownMesh = pickResult.pickedMesh;
  12999. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  13000. switch (evt.button) {
  13001. case 0:
  13002. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13003. break;
  13004. case 1:
  13005. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13006. break;
  13007. case 2:
  13008. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13009. break;
  13010. }
  13011. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13012. }
  13013. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  13014. var that = _this;
  13015. window.setTimeout(function () {
  13016. 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);
  13017. if (pickResult.hit && pickResult.pickedMesh) {
  13018. if (pickResult.pickedMesh.actionManager) {
  13019. 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)) {
  13020. that._startingPointerTime = 0;
  13021. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13022. }
  13023. }
  13024. }
  13025. }, BABYLON.ActionManager.LongPressDelay);
  13026. }
  13027. }
  13028. }
  13029. if (_this.onPointerDown) {
  13030. _this.onPointerDown(evt, pickResult);
  13031. }
  13032. // Sprites
  13033. _this._pickedDownSprite = null;
  13034. if (_this.spriteManagers.length > 0) {
  13035. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13036. if (pickResult.hit && pickResult.pickedSprite) {
  13037. if (pickResult.pickedSprite.actionManager) {
  13038. _this._pickedDownSprite = pickResult.pickedSprite;
  13039. switch (evt.button) {
  13040. case 0:
  13041. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13042. break;
  13043. case 1:
  13044. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13045. break;
  13046. case 2:
  13047. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13048. break;
  13049. }
  13050. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13051. }
  13052. }
  13053. }
  13054. };
  13055. this._onPointerUp = function (evt) {
  13056. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13057. return;
  13058. }
  13059. _this._updatePointerPosition(evt);
  13060. if (!_this.pointerUpPredicate) {
  13061. _this.pointerUpPredicate = function (mesh) {
  13062. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  13063. };
  13064. }
  13065. // Meshes
  13066. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  13067. if (pickResult.hit && pickResult.pickedMesh) {
  13068. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  13069. _this.onPointerPick(evt, pickResult);
  13070. }
  13071. if (pickResult.pickedMesh.actionManager) {
  13072. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13073. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13074. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13075. }
  13076. }
  13077. }
  13078. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  13079. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  13080. }
  13081. if (_this.onPointerUp) {
  13082. _this.onPointerUp(evt, pickResult);
  13083. }
  13084. _this._startingPointerTime = 0;
  13085. // Sprites
  13086. if (_this.spriteManagers.length > 0) {
  13087. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13088. if (pickResult.hit && pickResult.pickedSprite) {
  13089. if (pickResult.pickedSprite.actionManager) {
  13090. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13091. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13092. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13093. }
  13094. }
  13095. }
  13096. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  13097. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  13098. }
  13099. }
  13100. };
  13101. this._onKeyDown = function (evt) {
  13102. if (_this.actionManager) {
  13103. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13104. }
  13105. };
  13106. this._onKeyUp = function (evt) {
  13107. if (_this.actionManager) {
  13108. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13109. }
  13110. };
  13111. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13112. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  13113. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  13114. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  13115. // Wheel
  13116. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  13117. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  13118. BABYLON.Tools.RegisterTopRootEvents([
  13119. { name: "keydown", handler: this._onKeyDown },
  13120. { name: "keyup", handler: this._onKeyUp }
  13121. ]);
  13122. };
  13123. Scene.prototype.detachControl = function () {
  13124. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13125. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  13126. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  13127. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  13128. // Wheel
  13129. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  13130. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  13131. BABYLON.Tools.UnregisterTopRootEvents([
  13132. { name: "keydown", handler: this._onKeyDown },
  13133. { name: "keyup", handler: this._onKeyUp }
  13134. ]);
  13135. };
  13136. // Ready
  13137. Scene.prototype.isReady = function () {
  13138. if (this._pendingData.length > 0) {
  13139. return false;
  13140. }
  13141. var index;
  13142. for (index = 0; index < this._geometries.length; index++) {
  13143. var geometry = this._geometries[index];
  13144. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13145. return false;
  13146. }
  13147. }
  13148. for (index = 0; index < this.meshes.length; index++) {
  13149. var mesh = this.meshes[index];
  13150. if (!mesh.isReady()) {
  13151. return false;
  13152. }
  13153. var mat = mesh.material;
  13154. if (mat) {
  13155. if (!mat.isReady(mesh)) {
  13156. return false;
  13157. }
  13158. }
  13159. }
  13160. return true;
  13161. };
  13162. Scene.prototype.resetCachedMaterial = function () {
  13163. this._cachedMaterial = null;
  13164. };
  13165. Scene.prototype.registerBeforeRender = function (func) {
  13166. this._onBeforeRenderCallbacks.push(func);
  13167. };
  13168. Scene.prototype.unregisterBeforeRender = function (func) {
  13169. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13170. if (index > -1) {
  13171. this._onBeforeRenderCallbacks.splice(index, 1);
  13172. }
  13173. };
  13174. Scene.prototype.registerAfterRender = function (func) {
  13175. this._onAfterRenderCallbacks.push(func);
  13176. };
  13177. Scene.prototype.unregisterAfterRender = function (func) {
  13178. var index = this._onAfterRenderCallbacks.indexOf(func);
  13179. if (index > -1) {
  13180. this._onAfterRenderCallbacks.splice(index, 1);
  13181. }
  13182. };
  13183. Scene.prototype._addPendingData = function (data) {
  13184. this._pendingData.push(data);
  13185. };
  13186. Scene.prototype._removePendingData = function (data) {
  13187. var index = this._pendingData.indexOf(data);
  13188. if (index !== -1) {
  13189. this._pendingData.splice(index, 1);
  13190. }
  13191. };
  13192. Scene.prototype.getWaitingItemsCount = function () {
  13193. return this._pendingData.length;
  13194. };
  13195. /**
  13196. * Registers a function to be executed when the scene is ready.
  13197. * @param {Function} func - the function to be executed.
  13198. */
  13199. Scene.prototype.executeWhenReady = function (func) {
  13200. var _this = this;
  13201. this._onReadyCallbacks.push(func);
  13202. if (this._executeWhenReadyTimeoutId !== -1) {
  13203. return;
  13204. }
  13205. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13206. _this._checkIsReady();
  13207. }, 150);
  13208. };
  13209. Scene.prototype._checkIsReady = function () {
  13210. var _this = this;
  13211. if (this.isReady()) {
  13212. this._onReadyCallbacks.forEach(function (func) {
  13213. func();
  13214. });
  13215. this._onReadyCallbacks = [];
  13216. this._executeWhenReadyTimeoutId = -1;
  13217. return;
  13218. }
  13219. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13220. _this._checkIsReady();
  13221. }, 150);
  13222. };
  13223. // Animations
  13224. /**
  13225. * Will start the animation sequence of a given target
  13226. * @param target - the target
  13227. * @param {number} from - from which frame should animation start
  13228. * @param {number} to - till which frame should animation run.
  13229. * @param {boolean} [loop] - should the animation loop
  13230. * @param {number} [speedRatio] - the speed in which to run the animation
  13231. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  13232. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  13233. * @return {BABYLON.Animatable} the animatable object created for this animation
  13234. * @see BABYLON.Animatable
  13235. * @see http://doc.babylonjs.com/page.php?p=22081
  13236. */
  13237. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  13238. if (speedRatio === void 0) { speedRatio = 1.0; }
  13239. this.stopAnimation(target);
  13240. if (!animatable) {
  13241. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  13242. }
  13243. // Local animations
  13244. if (target.animations) {
  13245. animatable.appendAnimations(target, target.animations);
  13246. }
  13247. // Children animations
  13248. if (target.getAnimatables) {
  13249. var animatables = target.getAnimatables();
  13250. for (var index = 0; index < animatables.length; index++) {
  13251. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  13252. }
  13253. }
  13254. return animatable;
  13255. };
  13256. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  13257. if (speedRatio === undefined) {
  13258. speedRatio = 1.0;
  13259. }
  13260. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  13261. return animatable;
  13262. };
  13263. Scene.prototype.getAnimatableByTarget = function (target) {
  13264. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13265. if (this._activeAnimatables[index].target === target) {
  13266. return this._activeAnimatables[index];
  13267. }
  13268. }
  13269. return null;
  13270. };
  13271. Object.defineProperty(Scene.prototype, "Animatables", {
  13272. get: function () {
  13273. return this._activeAnimatables;
  13274. },
  13275. enumerable: true,
  13276. configurable: true
  13277. });
  13278. /**
  13279. * Will stop the animation of the given target
  13280. * @param target - the target
  13281. * @see beginAnimation
  13282. */
  13283. Scene.prototype.stopAnimation = function (target) {
  13284. var animatable = this.getAnimatableByTarget(target);
  13285. if (animatable) {
  13286. animatable.stop();
  13287. }
  13288. };
  13289. Scene.prototype._animate = function () {
  13290. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  13291. return;
  13292. }
  13293. if (!this._animationStartDate) {
  13294. if (this._pendingData.length > 0) {
  13295. return;
  13296. }
  13297. this._animationStartDate = BABYLON.Tools.Now;
  13298. }
  13299. // Getting time
  13300. var now = BABYLON.Tools.Now;
  13301. var delay = now - this._animationStartDate;
  13302. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13303. this._activeAnimatables[index]._animate(delay);
  13304. }
  13305. };
  13306. // Matrix
  13307. Scene.prototype.getViewMatrix = function () {
  13308. return this._viewMatrix;
  13309. };
  13310. Scene.prototype.getProjectionMatrix = function () {
  13311. return this._projectionMatrix;
  13312. };
  13313. Scene.prototype.getTransformMatrix = function () {
  13314. return this._transformMatrix;
  13315. };
  13316. Scene.prototype.setTransformMatrix = function (view, projection) {
  13317. this._viewMatrix = view;
  13318. this._projectionMatrix = projection;
  13319. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13320. };
  13321. // Methods
  13322. Scene.prototype.addMesh = function (newMesh) {
  13323. newMesh.uniqueId = this._uniqueIdCounter++;
  13324. var position = this.meshes.push(newMesh);
  13325. //notify the collision coordinator
  13326. this.collisionCoordinator.onMeshAdded(newMesh);
  13327. if (this.onNewMeshAdded) {
  13328. this.onNewMeshAdded(newMesh, position, this);
  13329. }
  13330. };
  13331. Scene.prototype.removeMesh = function (toRemove) {
  13332. var index = this.meshes.indexOf(toRemove);
  13333. if (index !== -1) {
  13334. // Remove from the scene if mesh found
  13335. this.meshes.splice(index, 1);
  13336. }
  13337. //notify the collision coordinator
  13338. this.collisionCoordinator.onMeshRemoved(toRemove);
  13339. if (this.onMeshRemoved) {
  13340. this.onMeshRemoved(toRemove);
  13341. }
  13342. return index;
  13343. };
  13344. Scene.prototype.removeSkeleton = function (toRemove) {
  13345. var index = this.skeletons.indexOf(toRemove);
  13346. if (index !== -1) {
  13347. // Remove from the scene if mesh found
  13348. this.skeletons.splice(index, 1);
  13349. }
  13350. return index;
  13351. };
  13352. Scene.prototype.removeLight = function (toRemove) {
  13353. var index = this.lights.indexOf(toRemove);
  13354. if (index !== -1) {
  13355. // Remove from the scene if mesh found
  13356. this.lights.splice(index, 1);
  13357. }
  13358. if (this.onLightRemoved) {
  13359. this.onLightRemoved(toRemove);
  13360. }
  13361. return index;
  13362. };
  13363. Scene.prototype.removeCamera = function (toRemove) {
  13364. var index = this.cameras.indexOf(toRemove);
  13365. if (index !== -1) {
  13366. // Remove from the scene if mesh found
  13367. this.cameras.splice(index, 1);
  13368. }
  13369. // Remove from activeCameras
  13370. var index2 = this.activeCameras.indexOf(toRemove);
  13371. if (index2 !== -1) {
  13372. // Remove from the scene if mesh found
  13373. this.activeCameras.splice(index2, 1);
  13374. }
  13375. // Reset the activeCamera
  13376. if (this.activeCamera === toRemove) {
  13377. if (this.cameras.length > 0) {
  13378. this.activeCamera = this.cameras[0];
  13379. }
  13380. else {
  13381. this.activeCamera = null;
  13382. }
  13383. }
  13384. if (this.onCameraRemoved) {
  13385. this.onCameraRemoved(toRemove);
  13386. }
  13387. return index;
  13388. };
  13389. Scene.prototype.addLight = function (newLight) {
  13390. newLight.uniqueId = this._uniqueIdCounter++;
  13391. var position = this.lights.push(newLight);
  13392. if (this.onNewLightAdded) {
  13393. this.onNewLightAdded(newLight, position, this);
  13394. }
  13395. };
  13396. Scene.prototype.addCamera = function (newCamera) {
  13397. newCamera.uniqueId = this._uniqueIdCounter++;
  13398. var position = this.cameras.push(newCamera);
  13399. if (this.onNewCameraAdded) {
  13400. this.onNewCameraAdded(newCamera, position, this);
  13401. }
  13402. };
  13403. /**
  13404. * Switch active camera
  13405. * @param {Camera} newCamera - new active camera
  13406. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13407. */
  13408. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13409. if (attachControl === void 0) { attachControl = true; }
  13410. var canvas = this._engine.getRenderingCanvas();
  13411. this.activeCamera.detachControl(canvas);
  13412. this.activeCamera = newCamera;
  13413. if (attachControl) {
  13414. newCamera.attachControl(canvas);
  13415. }
  13416. };
  13417. /**
  13418. * sets the active camera of the scene using its ID
  13419. * @param {string} id - the camera's ID
  13420. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13421. * @see activeCamera
  13422. */
  13423. Scene.prototype.setActiveCameraByID = function (id) {
  13424. var camera = this.getCameraByID(id);
  13425. if (camera) {
  13426. this.activeCamera = camera;
  13427. return camera;
  13428. }
  13429. return null;
  13430. };
  13431. /**
  13432. * sets the active camera of the scene using its name
  13433. * @param {string} name - the camera's name
  13434. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13435. * @see activeCamera
  13436. */
  13437. Scene.prototype.setActiveCameraByName = function (name) {
  13438. var camera = this.getCameraByName(name);
  13439. if (camera) {
  13440. this.activeCamera = camera;
  13441. return camera;
  13442. }
  13443. return null;
  13444. };
  13445. /**
  13446. * get a material using its id
  13447. * @param {string} the material's ID
  13448. * @return {BABYLON.Material|null} the material or null if none found.
  13449. */
  13450. Scene.prototype.getMaterialByID = function (id) {
  13451. for (var index = 0; index < this.materials.length; index++) {
  13452. if (this.materials[index].id === id) {
  13453. return this.materials[index];
  13454. }
  13455. }
  13456. return null;
  13457. };
  13458. /**
  13459. * get a material using its name
  13460. * @param {string} the material's name
  13461. * @return {BABYLON.Material|null} the material or null if none found.
  13462. */
  13463. Scene.prototype.getMaterialByName = function (name) {
  13464. for (var index = 0; index < this.materials.length; index++) {
  13465. if (this.materials[index].name === name) {
  13466. return this.materials[index];
  13467. }
  13468. }
  13469. return null;
  13470. };
  13471. Scene.prototype.getLensFlareSystemByName = function (name) {
  13472. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13473. if (this.lensFlareSystems[index].name === name) {
  13474. return this.lensFlareSystems[index];
  13475. }
  13476. }
  13477. return null;
  13478. };
  13479. Scene.prototype.getCameraByID = function (id) {
  13480. for (var index = 0; index < this.cameras.length; index++) {
  13481. if (this.cameras[index].id === id) {
  13482. return this.cameras[index];
  13483. }
  13484. }
  13485. return null;
  13486. };
  13487. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13488. for (var index = 0; index < this.cameras.length; index++) {
  13489. if (this.cameras[index].uniqueId === uniqueId) {
  13490. return this.cameras[index];
  13491. }
  13492. }
  13493. return null;
  13494. };
  13495. /**
  13496. * get a camera using its name
  13497. * @param {string} the camera's name
  13498. * @return {BABYLON.Camera|null} the camera or null if none found.
  13499. */
  13500. Scene.prototype.getCameraByName = function (name) {
  13501. for (var index = 0; index < this.cameras.length; index++) {
  13502. if (this.cameras[index].name === name) {
  13503. return this.cameras[index];
  13504. }
  13505. }
  13506. return null;
  13507. };
  13508. /**
  13509. * get a bone using its id
  13510. * @param {string} the bone's id
  13511. * @return {BABYLON.Bone|null} the bone or null if not found
  13512. */
  13513. Scene.prototype.getBoneByID = function (id) {
  13514. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13515. var skeleton = this.skeletons[skeletonIndex];
  13516. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13517. if (skeleton.bones[boneIndex].id === id) {
  13518. return skeleton.bones[boneIndex];
  13519. }
  13520. }
  13521. }
  13522. return null;
  13523. };
  13524. /**
  13525. * get a bone using its id
  13526. * @param {string} the bone's name
  13527. * @return {BABYLON.Bone|null} the bone or null if not found
  13528. */
  13529. Scene.prototype.getBoneByName = function (name) {
  13530. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13531. var skeleton = this.skeletons[skeletonIndex];
  13532. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13533. if (skeleton.bones[boneIndex].name === name) {
  13534. return skeleton.bones[boneIndex];
  13535. }
  13536. }
  13537. }
  13538. return null;
  13539. };
  13540. /**
  13541. * get a light node using its name
  13542. * @param {string} the light's name
  13543. * @return {BABYLON.Light|null} the light or null if none found.
  13544. */
  13545. Scene.prototype.getLightByName = function (name) {
  13546. for (var index = 0; index < this.lights.length; index++) {
  13547. if (this.lights[index].name === name) {
  13548. return this.lights[index];
  13549. }
  13550. }
  13551. return null;
  13552. };
  13553. /**
  13554. * get a light node using its ID
  13555. * @param {string} the light's id
  13556. * @return {BABYLON.Light|null} the light or null if none found.
  13557. */
  13558. Scene.prototype.getLightByID = function (id) {
  13559. for (var index = 0; index < this.lights.length; index++) {
  13560. if (this.lights[index].id === id) {
  13561. return this.lights[index];
  13562. }
  13563. }
  13564. return null;
  13565. };
  13566. /**
  13567. * get a light node using its scene-generated unique ID
  13568. * @param {number} the light's unique id
  13569. * @return {BABYLON.Light|null} the light or null if none found.
  13570. */
  13571. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13572. for (var index = 0; index < this.lights.length; index++) {
  13573. if (this.lights[index].uniqueId === uniqueId) {
  13574. return this.lights[index];
  13575. }
  13576. }
  13577. return null;
  13578. };
  13579. /**
  13580. * get a particle system by id
  13581. * @param id {number} the particle system id
  13582. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13583. */
  13584. Scene.prototype.getParticleSystemByID = function (id) {
  13585. for (var index = 0; index < this.particleSystems.length; index++) {
  13586. if (this.particleSystems[index].id === id) {
  13587. return this.particleSystems[index];
  13588. }
  13589. }
  13590. return null;
  13591. };
  13592. /**
  13593. * get a geometry using its ID
  13594. * @param {string} the geometry's id
  13595. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13596. */
  13597. Scene.prototype.getGeometryByID = function (id) {
  13598. for (var index = 0; index < this._geometries.length; index++) {
  13599. if (this._geometries[index].id === id) {
  13600. return this._geometries[index];
  13601. }
  13602. }
  13603. return null;
  13604. };
  13605. /**
  13606. * add a new geometry to this scene.
  13607. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13608. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13609. * @return {boolean} was the geometry added or not
  13610. */
  13611. Scene.prototype.pushGeometry = function (geometry, force) {
  13612. if (!force && this.getGeometryByID(geometry.id)) {
  13613. return false;
  13614. }
  13615. this._geometries.push(geometry);
  13616. //notify the collision coordinator
  13617. this.collisionCoordinator.onGeometryAdded(geometry);
  13618. if (this.onGeometryAdded) {
  13619. this.onGeometryAdded(geometry);
  13620. }
  13621. return true;
  13622. };
  13623. /**
  13624. * Removes an existing geometry
  13625. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13626. * @return {boolean} was the geometry removed or not
  13627. */
  13628. Scene.prototype.removeGeometry = function (geometry) {
  13629. var index = this._geometries.indexOf(geometry);
  13630. if (index > -1) {
  13631. this._geometries.splice(index, 1);
  13632. //notify the collision coordinator
  13633. this.collisionCoordinator.onGeometryDeleted(geometry);
  13634. if (this.onGeometryRemoved) {
  13635. this.onGeometryRemoved(geometry);
  13636. }
  13637. return true;
  13638. }
  13639. return false;
  13640. };
  13641. Scene.prototype.getGeometries = function () {
  13642. return this._geometries;
  13643. };
  13644. /**
  13645. * Get the first added mesh found of a given ID
  13646. * @param {string} id - the id to search for
  13647. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13648. */
  13649. Scene.prototype.getMeshByID = function (id) {
  13650. for (var index = 0; index < this.meshes.length; index++) {
  13651. if (this.meshes[index].id === id) {
  13652. return this.meshes[index];
  13653. }
  13654. }
  13655. return null;
  13656. };
  13657. /**
  13658. * Get a mesh with its auto-generated unique id
  13659. * @param {number} uniqueId - the unique id to search for
  13660. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13661. */
  13662. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13663. for (var index = 0; index < this.meshes.length; index++) {
  13664. if (this.meshes[index].uniqueId === uniqueId) {
  13665. return this.meshes[index];
  13666. }
  13667. }
  13668. return null;
  13669. };
  13670. /**
  13671. * Get a the last added mesh found of a given ID
  13672. * @param {string} id - the id to search for
  13673. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13674. */
  13675. Scene.prototype.getLastMeshByID = function (id) {
  13676. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13677. if (this.meshes[index].id === id) {
  13678. return this.meshes[index];
  13679. }
  13680. }
  13681. return null;
  13682. };
  13683. /**
  13684. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13685. * @param {string} id - the id to search for
  13686. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13687. */
  13688. Scene.prototype.getLastEntryByID = function (id) {
  13689. var index;
  13690. for (index = this.meshes.length - 1; index >= 0; index--) {
  13691. if (this.meshes[index].id === id) {
  13692. return this.meshes[index];
  13693. }
  13694. }
  13695. for (index = this.cameras.length - 1; index >= 0; index--) {
  13696. if (this.cameras[index].id === id) {
  13697. return this.cameras[index];
  13698. }
  13699. }
  13700. for (index = this.lights.length - 1; index >= 0; index--) {
  13701. if (this.lights[index].id === id) {
  13702. return this.lights[index];
  13703. }
  13704. }
  13705. return null;
  13706. };
  13707. Scene.prototype.getNodeByID = function (id) {
  13708. var mesh = this.getMeshByID(id);
  13709. if (mesh) {
  13710. return mesh;
  13711. }
  13712. var light = this.getLightByID(id);
  13713. if (light) {
  13714. return light;
  13715. }
  13716. var camera = this.getCameraByID(id);
  13717. if (camera) {
  13718. return camera;
  13719. }
  13720. var bone = this.getBoneByID(id);
  13721. return bone;
  13722. };
  13723. Scene.prototype.getNodeByName = function (name) {
  13724. var mesh = this.getMeshByName(name);
  13725. if (mesh) {
  13726. return mesh;
  13727. }
  13728. var light = this.getLightByName(name);
  13729. if (light) {
  13730. return light;
  13731. }
  13732. var camera = this.getCameraByName(name);
  13733. if (camera) {
  13734. return camera;
  13735. }
  13736. var bone = this.getBoneByName(name);
  13737. return bone;
  13738. };
  13739. Scene.prototype.getMeshByName = function (name) {
  13740. for (var index = 0; index < this.meshes.length; index++) {
  13741. if (this.meshes[index].name === name) {
  13742. return this.meshes[index];
  13743. }
  13744. }
  13745. return null;
  13746. };
  13747. Scene.prototype.getSoundByName = function (name) {
  13748. var index;
  13749. if (BABYLON.AudioEngine) {
  13750. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13751. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13752. return this.mainSoundTrack.soundCollection[index];
  13753. }
  13754. }
  13755. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13756. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13757. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13758. return this.soundTracks[sdIndex].soundCollection[index];
  13759. }
  13760. }
  13761. }
  13762. }
  13763. return null;
  13764. };
  13765. Scene.prototype.getLastSkeletonByID = function (id) {
  13766. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13767. if (this.skeletons[index].id === id) {
  13768. return this.skeletons[index];
  13769. }
  13770. }
  13771. return null;
  13772. };
  13773. Scene.prototype.getSkeletonById = function (id) {
  13774. for (var index = 0; index < this.skeletons.length; index++) {
  13775. if (this.skeletons[index].id === id) {
  13776. return this.skeletons[index];
  13777. }
  13778. }
  13779. return null;
  13780. };
  13781. Scene.prototype.getSkeletonByName = function (name) {
  13782. for (var index = 0; index < this.skeletons.length; index++) {
  13783. if (this.skeletons[index].name === name) {
  13784. return this.skeletons[index];
  13785. }
  13786. }
  13787. return null;
  13788. };
  13789. Scene.prototype.isActiveMesh = function (mesh) {
  13790. return (this._activeMeshes.indexOf(mesh) !== -1);
  13791. };
  13792. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13793. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13794. var material = subMesh.getMaterial();
  13795. if (mesh.showSubMeshesBoundingBox) {
  13796. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13797. }
  13798. if (material) {
  13799. // Render targets
  13800. if (material.getRenderTargetTextures) {
  13801. if (this._processedMaterials.indexOf(material) === -1) {
  13802. this._processedMaterials.push(material);
  13803. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13804. }
  13805. }
  13806. // Dispatch
  13807. this._activeIndices += subMesh.indexCount;
  13808. this._renderingManager.dispatch(subMesh);
  13809. }
  13810. }
  13811. };
  13812. Scene.prototype._evaluateActiveMeshes = function () {
  13813. this.activeCamera._activeMeshes.reset();
  13814. this._activeMeshes.reset();
  13815. this._renderingManager.reset();
  13816. this._processedMaterials.reset();
  13817. this._activeParticleSystems.reset();
  13818. this._activeSkeletons.reset();
  13819. this._softwareSkinnedMeshes.reset();
  13820. this._boundingBoxRenderer.reset();
  13821. this._edgesRenderers.reset();
  13822. if (!this._frustumPlanes) {
  13823. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13824. }
  13825. else {
  13826. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13827. }
  13828. // Meshes
  13829. var meshes;
  13830. var len;
  13831. if (this._selectionOctree) {
  13832. var selection = this._selectionOctree.select(this._frustumPlanes);
  13833. meshes = selection.data;
  13834. len = selection.length;
  13835. }
  13836. else {
  13837. len = this.meshes.length;
  13838. meshes = this.meshes;
  13839. }
  13840. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13841. var mesh = meshes[meshIndex];
  13842. if (mesh.isBlocked) {
  13843. continue;
  13844. }
  13845. this._totalVertices += mesh.getTotalVertices();
  13846. if (!mesh.isReady() || !mesh.isEnabled()) {
  13847. continue;
  13848. }
  13849. mesh.computeWorldMatrix();
  13850. // Intersections
  13851. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13852. this._meshesForIntersections.pushNoDuplicate(mesh);
  13853. }
  13854. // Switch to current LOD
  13855. var meshLOD = mesh.getLOD(this.activeCamera);
  13856. if (!meshLOD) {
  13857. continue;
  13858. }
  13859. mesh._preActivate();
  13860. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13861. this._activeMeshes.push(mesh);
  13862. this.activeCamera._activeMeshes.push(mesh);
  13863. mesh._activate(this._renderId);
  13864. this._activeMesh(meshLOD);
  13865. }
  13866. }
  13867. // Particle systems
  13868. var beforeParticlesDate = BABYLON.Tools.Now;
  13869. if (this.particlesEnabled) {
  13870. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13871. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13872. var particleSystem = this.particleSystems[particleIndex];
  13873. if (!particleSystem.isStarted()) {
  13874. continue;
  13875. }
  13876. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13877. this._activeParticleSystems.push(particleSystem);
  13878. particleSystem.animate();
  13879. }
  13880. }
  13881. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13882. }
  13883. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13884. };
  13885. Scene.prototype._activeMesh = function (mesh) {
  13886. if (mesh.skeleton && this.skeletonsEnabled) {
  13887. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13888. if (!mesh.computeBonesUsingShaders) {
  13889. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13890. }
  13891. }
  13892. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13893. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13894. }
  13895. if (mesh._edgesRenderer) {
  13896. this._edgesRenderers.push(mesh._edgesRenderer);
  13897. }
  13898. if (mesh && mesh.subMeshes) {
  13899. // Submeshes Octrees
  13900. var len;
  13901. var subMeshes;
  13902. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13903. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13904. len = intersections.length;
  13905. subMeshes = intersections.data;
  13906. }
  13907. else {
  13908. subMeshes = mesh.subMeshes;
  13909. len = subMeshes.length;
  13910. }
  13911. for (var subIndex = 0; subIndex < len; subIndex++) {
  13912. var subMesh = subMeshes[subIndex];
  13913. this._evaluateSubMesh(subMesh, mesh);
  13914. }
  13915. }
  13916. };
  13917. Scene.prototype.updateTransformMatrix = function (force) {
  13918. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13919. };
  13920. Scene.prototype._renderForCamera = function (camera) {
  13921. var engine = this._engine;
  13922. this.activeCamera = camera;
  13923. if (!this.activeCamera)
  13924. throw new Error("Active camera not set");
  13925. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13926. // Viewport
  13927. engine.setViewport(this.activeCamera.viewport);
  13928. // Camera
  13929. this.resetCachedMaterial();
  13930. this._renderId++;
  13931. this.updateTransformMatrix();
  13932. if (this.beforeCameraRender) {
  13933. this.beforeCameraRender(this.activeCamera);
  13934. }
  13935. // Meshes
  13936. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13937. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13938. this._evaluateActiveMeshes();
  13939. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13940. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13941. // Skeletons
  13942. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13943. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13944. skeleton.prepare();
  13945. }
  13946. // Software skinning
  13947. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13948. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13949. mesh.applySkeleton(mesh.skeleton);
  13950. }
  13951. // Render targets
  13952. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13953. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13954. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13955. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13956. var renderTarget = this._renderTargets.data[renderIndex];
  13957. if (renderTarget._shouldRender()) {
  13958. this._renderId++;
  13959. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13960. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13961. }
  13962. }
  13963. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13964. this._renderId++;
  13965. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13966. }
  13967. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13968. // Prepare Frame
  13969. this.postProcessManager._prepareFrame();
  13970. var beforeRenderDate = BABYLON.Tools.Now;
  13971. // Backgrounds
  13972. var layerIndex;
  13973. var layer;
  13974. if (this.layers.length) {
  13975. engine.setDepthBuffer(false);
  13976. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13977. layer = this.layers[layerIndex];
  13978. if (layer.isBackground) {
  13979. layer.render();
  13980. }
  13981. }
  13982. engine.setDepthBuffer(true);
  13983. }
  13984. // Render
  13985. BABYLON.Tools.StartPerformanceCounter("Main render");
  13986. this._renderingManager.render(null, null, true, true);
  13987. BABYLON.Tools.EndPerformanceCounter("Main render");
  13988. // Bounding boxes
  13989. this._boundingBoxRenderer.render();
  13990. // Edges
  13991. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13992. this._edgesRenderers.data[edgesRendererIndex].render();
  13993. }
  13994. // Lens flares
  13995. if (this.lensFlaresEnabled) {
  13996. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13997. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13998. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13999. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  14000. lensFlareSystem.render();
  14001. }
  14002. }
  14003. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  14004. }
  14005. // Foregrounds
  14006. if (this.layers.length) {
  14007. engine.setDepthBuffer(false);
  14008. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  14009. layer = this.layers[layerIndex];
  14010. if (!layer.isBackground) {
  14011. layer.render();
  14012. }
  14013. }
  14014. engine.setDepthBuffer(true);
  14015. }
  14016. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  14017. // Finalize frame
  14018. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  14019. // Update camera
  14020. this.activeCamera._updateFromScene();
  14021. // Reset some special arrays
  14022. this._renderTargets.reset();
  14023. if (this.afterCameraRender) {
  14024. this.afterCameraRender(this.activeCamera);
  14025. }
  14026. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  14027. };
  14028. Scene.prototype._processSubCameras = function (camera) {
  14029. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  14030. this._renderForCamera(camera);
  14031. return;
  14032. }
  14033. // rig cameras
  14034. for (var index = 0; index < camera._rigCameras.length; index++) {
  14035. this._renderForCamera(camera._rigCameras[index]);
  14036. }
  14037. this.activeCamera = camera;
  14038. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  14039. // Update camera
  14040. this.activeCamera._updateFromScene();
  14041. };
  14042. Scene.prototype._checkIntersections = function () {
  14043. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  14044. var sourceMesh = this._meshesForIntersections.data[index];
  14045. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  14046. var action = sourceMesh.actionManager.actions[actionIndex];
  14047. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14048. var parameters = action.getTriggerParameter();
  14049. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  14050. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  14051. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  14052. if (areIntersecting && currentIntersectionInProgress === -1) {
  14053. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  14054. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14055. sourceMesh._intersectionsInProgress.push(otherMesh);
  14056. }
  14057. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14058. sourceMesh._intersectionsInProgress.push(otherMesh);
  14059. }
  14060. }
  14061. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  14062. //They intersected, and now they don't.
  14063. //is this trigger an exit trigger? execute an event.
  14064. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14065. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14066. }
  14067. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  14068. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14069. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  14070. }
  14071. }
  14072. }
  14073. }
  14074. }
  14075. };
  14076. Scene.prototype.render = function () {
  14077. var startDate = BABYLON.Tools.Now;
  14078. this._particlesDuration = 0;
  14079. this._spritesDuration = 0;
  14080. this._activeParticles = 0;
  14081. this._renderDuration = 0;
  14082. this._renderTargetsDuration = 0;
  14083. this._evaluateActiveMeshesDuration = 0;
  14084. this._totalVertices = 0;
  14085. this._activeIndices = 0;
  14086. this._activeBones = 0;
  14087. this.getEngine().resetDrawCalls();
  14088. this._meshesForIntersections.reset();
  14089. this.resetCachedMaterial();
  14090. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  14091. // Actions
  14092. if (this.actionManager) {
  14093. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  14094. }
  14095. //Simplification Queue
  14096. if (this.simplificationQueue && !this.simplificationQueue.running) {
  14097. this.simplificationQueue.executeNext();
  14098. }
  14099. // Animations
  14100. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  14101. this._animationRatio = deltaTime * (60.0 / 1000.0);
  14102. this._animate();
  14103. // Physics
  14104. if (this._physicsEngine) {
  14105. BABYLON.Tools.StartPerformanceCounter("Physics");
  14106. this._physicsEngine._step(deltaTime / 1000.0);
  14107. BABYLON.Tools.EndPerformanceCounter("Physics");
  14108. }
  14109. // Before render
  14110. if (this.beforeRender) {
  14111. this.beforeRender();
  14112. }
  14113. var callbackIndex;
  14114. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14115. this._onBeforeRenderCallbacks[callbackIndex]();
  14116. }
  14117. // Customs render targets
  14118. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14119. var engine = this.getEngine();
  14120. var currentActiveCamera = this.activeCamera;
  14121. if (this.renderTargetsEnabled) {
  14122. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14123. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  14124. var renderTarget = this.customRenderTargets[customIndex];
  14125. if (renderTarget._shouldRender()) {
  14126. this._renderId++;
  14127. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  14128. if (!this.activeCamera)
  14129. throw new Error("Active camera not set");
  14130. // Viewport
  14131. engine.setViewport(this.activeCamera.viewport);
  14132. // Camera
  14133. this.updateTransformMatrix();
  14134. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  14135. }
  14136. }
  14137. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14138. this._renderId++;
  14139. }
  14140. if (this.customRenderTargets.length > 0) {
  14141. engine.restoreDefaultFramebuffer();
  14142. }
  14143. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14144. this.activeCamera = currentActiveCamera;
  14145. // Procedural textures
  14146. if (this.proceduralTexturesEnabled) {
  14147. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14148. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  14149. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  14150. if (proceduralTexture._shouldRender()) {
  14151. proceduralTexture.render();
  14152. }
  14153. }
  14154. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14155. }
  14156. // Clear
  14157. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  14158. // Shadows
  14159. if (this.shadowsEnabled) {
  14160. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  14161. var light = this.lights[lightIndex];
  14162. var shadowGenerator = light.getShadowGenerator();
  14163. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  14164. this._renderTargets.push(shadowGenerator.getShadowMap());
  14165. }
  14166. }
  14167. }
  14168. // Depth renderer
  14169. if (this._depthRenderer) {
  14170. this._renderTargets.push(this._depthRenderer.getDepthMap());
  14171. }
  14172. // RenderPipeline
  14173. this.postProcessRenderPipelineManager.update();
  14174. // Multi-cameras?
  14175. if (this.activeCameras.length > 0) {
  14176. var currentRenderId = this._renderId;
  14177. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  14178. this._renderId = currentRenderId;
  14179. if (cameraIndex > 0) {
  14180. this._engine.clear(0, false, true);
  14181. }
  14182. this._processSubCameras(this.activeCameras[cameraIndex]);
  14183. }
  14184. }
  14185. else {
  14186. if (!this.activeCamera) {
  14187. throw new Error("No camera defined");
  14188. }
  14189. this._processSubCameras(this.activeCamera);
  14190. }
  14191. // Intersection checks
  14192. this._checkIntersections();
  14193. // Update the audio listener attached to the camera
  14194. if (BABYLON.AudioEngine) {
  14195. this._updateAudioParameters();
  14196. }
  14197. // After render
  14198. if (this.afterRender) {
  14199. this.afterRender();
  14200. }
  14201. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14202. this._onAfterRenderCallbacks[callbackIndex]();
  14203. }
  14204. // Cleaning
  14205. for (var index = 0; index < this._toBeDisposed.length; index++) {
  14206. this._toBeDisposed.data[index].dispose();
  14207. this._toBeDisposed[index] = null;
  14208. }
  14209. this._toBeDisposed.reset();
  14210. if (this.dumpNextRenderTargets) {
  14211. this.dumpNextRenderTargets = false;
  14212. }
  14213. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  14214. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  14215. };
  14216. Scene.prototype._updateAudioParameters = function () {
  14217. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  14218. return;
  14219. }
  14220. var listeningCamera;
  14221. var audioEngine = BABYLON.Engine.audioEngine;
  14222. if (this.activeCameras.length > 0) {
  14223. listeningCamera = this.activeCameras[0];
  14224. }
  14225. else {
  14226. listeningCamera = this.activeCamera;
  14227. }
  14228. if (listeningCamera && audioEngine.canUseWebAudio) {
  14229. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  14230. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  14231. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  14232. cameraDirection.normalize();
  14233. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  14234. var i;
  14235. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14236. var sound = this.mainSoundTrack.soundCollection[i];
  14237. if (sound.useCustomAttenuation) {
  14238. sound.updateDistanceFromListener();
  14239. }
  14240. }
  14241. for (i = 0; i < this.soundTracks.length; i++) {
  14242. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14243. sound = this.soundTracks[i].soundCollection[j];
  14244. if (sound.useCustomAttenuation) {
  14245. sound.updateDistanceFromListener();
  14246. }
  14247. }
  14248. }
  14249. }
  14250. };
  14251. Object.defineProperty(Scene.prototype, "audioEnabled", {
  14252. // Audio
  14253. get: function () {
  14254. return this._audioEnabled;
  14255. },
  14256. set: function (value) {
  14257. this._audioEnabled = value;
  14258. if (BABYLON.AudioEngine) {
  14259. if (this._audioEnabled) {
  14260. this._enableAudio();
  14261. }
  14262. else {
  14263. this._disableAudio();
  14264. }
  14265. }
  14266. },
  14267. enumerable: true,
  14268. configurable: true
  14269. });
  14270. Scene.prototype._disableAudio = function () {
  14271. var i;
  14272. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14273. this.mainSoundTrack.soundCollection[i].pause();
  14274. }
  14275. for (i = 0; i < this.soundTracks.length; i++) {
  14276. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14277. this.soundTracks[i].soundCollection[j].pause();
  14278. }
  14279. }
  14280. };
  14281. Scene.prototype._enableAudio = function () {
  14282. var i;
  14283. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14284. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  14285. this.mainSoundTrack.soundCollection[i].play();
  14286. }
  14287. }
  14288. for (i = 0; i < this.soundTracks.length; i++) {
  14289. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14290. if (this.soundTracks[i].soundCollection[j].isPaused) {
  14291. this.soundTracks[i].soundCollection[j].play();
  14292. }
  14293. }
  14294. }
  14295. };
  14296. Object.defineProperty(Scene.prototype, "headphone", {
  14297. get: function () {
  14298. return this._headphone;
  14299. },
  14300. set: function (value) {
  14301. this._headphone = value;
  14302. if (BABYLON.AudioEngine) {
  14303. if (this._headphone) {
  14304. this._switchAudioModeForHeadphones();
  14305. }
  14306. else {
  14307. this._switchAudioModeForNormalSpeakers();
  14308. }
  14309. }
  14310. },
  14311. enumerable: true,
  14312. configurable: true
  14313. });
  14314. Scene.prototype._switchAudioModeForHeadphones = function () {
  14315. this.mainSoundTrack.switchPanningModelToHRTF();
  14316. for (var i = 0; i < this.soundTracks.length; i++) {
  14317. this.soundTracks[i].switchPanningModelToHRTF();
  14318. }
  14319. };
  14320. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  14321. this.mainSoundTrack.switchPanningModelToEqualPower();
  14322. for (var i = 0; i < this.soundTracks.length; i++) {
  14323. this.soundTracks[i].switchPanningModelToEqualPower();
  14324. }
  14325. };
  14326. Scene.prototype.enableDepthRenderer = function () {
  14327. if (this._depthRenderer) {
  14328. return this._depthRenderer;
  14329. }
  14330. this._depthRenderer = new BABYLON.DepthRenderer(this);
  14331. return this._depthRenderer;
  14332. };
  14333. Scene.prototype.disableDepthRenderer = function () {
  14334. if (!this._depthRenderer) {
  14335. return;
  14336. }
  14337. this._depthRenderer.dispose();
  14338. this._depthRenderer = null;
  14339. };
  14340. Scene.prototype.freezeMaterials = function () {
  14341. for (var i = 0; i < this.materials.length; i++) {
  14342. this.materials[i].freeze();
  14343. }
  14344. };
  14345. Scene.prototype.unfreezeMaterials = function () {
  14346. for (var i = 0; i < this.materials.length; i++) {
  14347. this.materials[i].unfreeze();
  14348. }
  14349. };
  14350. Scene.prototype.dispose = function () {
  14351. this.beforeRender = null;
  14352. this.afterRender = null;
  14353. this.skeletons = [];
  14354. this._boundingBoxRenderer.dispose();
  14355. if (this._depthRenderer) {
  14356. this._depthRenderer.dispose();
  14357. }
  14358. // Debug layer
  14359. this.debugLayer.hide();
  14360. // Events
  14361. if (this.onDispose) {
  14362. this.onDispose();
  14363. }
  14364. this._onBeforeRenderCallbacks = [];
  14365. this._onAfterRenderCallbacks = [];
  14366. this.detachControl();
  14367. // Release sounds & sounds tracks
  14368. if (BABYLON.AudioEngine) {
  14369. this.disposeSounds();
  14370. }
  14371. // Detach cameras
  14372. var canvas = this._engine.getRenderingCanvas();
  14373. var index;
  14374. for (index = 0; index < this.cameras.length; index++) {
  14375. this.cameras[index].detachControl(canvas);
  14376. }
  14377. // Release lights
  14378. while (this.lights.length) {
  14379. this.lights[0].dispose();
  14380. }
  14381. // Release meshes
  14382. while (this.meshes.length) {
  14383. this.meshes[0].dispose(true);
  14384. }
  14385. // Release cameras
  14386. while (this.cameras.length) {
  14387. this.cameras[0].dispose();
  14388. }
  14389. // Release materials
  14390. while (this.materials.length) {
  14391. this.materials[0].dispose();
  14392. }
  14393. // Release particles
  14394. while (this.particleSystems.length) {
  14395. this.particleSystems[0].dispose();
  14396. }
  14397. // Release sprites
  14398. while (this.spriteManagers.length) {
  14399. this.spriteManagers[0].dispose();
  14400. }
  14401. // Release layers
  14402. while (this.layers.length) {
  14403. this.layers[0].dispose();
  14404. }
  14405. // Release textures
  14406. while (this.textures.length) {
  14407. this.textures[0].dispose();
  14408. }
  14409. // Post-processes
  14410. this.postProcessManager.dispose();
  14411. // Physics
  14412. if (this._physicsEngine) {
  14413. this.disablePhysicsEngine();
  14414. }
  14415. // Remove from engine
  14416. index = this._engine.scenes.indexOf(this);
  14417. if (index > -1) {
  14418. this._engine.scenes.splice(index, 1);
  14419. }
  14420. this._engine.wipeCaches();
  14421. };
  14422. // Release sounds & sounds tracks
  14423. Scene.prototype.disposeSounds = function () {
  14424. this.mainSoundTrack.dispose();
  14425. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14426. this.soundTracks[scIndex].dispose();
  14427. }
  14428. };
  14429. // Octrees
  14430. Scene.prototype.getWorldExtends = function () {
  14431. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14432. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14433. for (var index = 0; index < this.meshes.length; index++) {
  14434. var mesh = this.meshes[index];
  14435. mesh.computeWorldMatrix(true);
  14436. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14437. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14438. BABYLON.Tools.CheckExtends(minBox, min, max);
  14439. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14440. }
  14441. return {
  14442. min: min,
  14443. max: max
  14444. };
  14445. };
  14446. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14447. if (maxCapacity === void 0) { maxCapacity = 64; }
  14448. if (maxDepth === void 0) { maxDepth = 2; }
  14449. if (!this._selectionOctree) {
  14450. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14451. }
  14452. var worldExtends = this.getWorldExtends();
  14453. // Update octree
  14454. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14455. return this._selectionOctree;
  14456. };
  14457. // Picking
  14458. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14459. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14460. var engine = this._engine;
  14461. if (!camera) {
  14462. if (!this.activeCamera)
  14463. throw new Error("Active camera not set");
  14464. camera = this.activeCamera;
  14465. }
  14466. var cameraViewport = camera.viewport;
  14467. var viewport = cameraViewport.toGlobal(engine);
  14468. // Moving coordinates to local viewport world
  14469. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14470. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14471. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14472. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14473. };
  14474. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14475. var engine = this._engine;
  14476. if (!camera) {
  14477. if (!this.activeCamera)
  14478. throw new Error("Active camera not set");
  14479. camera = this.activeCamera;
  14480. }
  14481. var cameraViewport = camera.viewport;
  14482. var viewport = cameraViewport.toGlobal(engine);
  14483. var identity = BABYLON.Matrix.Identity();
  14484. // Moving coordinates to local viewport world
  14485. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14486. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14487. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14488. };
  14489. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14490. var pickingInfo = null;
  14491. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14492. var mesh = this.meshes[meshIndex];
  14493. if (predicate) {
  14494. if (!predicate(mesh)) {
  14495. continue;
  14496. }
  14497. }
  14498. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14499. continue;
  14500. }
  14501. var world = mesh.getWorldMatrix();
  14502. var ray = rayFunction(world);
  14503. var result = mesh.intersects(ray, fastCheck);
  14504. if (!result || !result.hit)
  14505. continue;
  14506. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14507. continue;
  14508. pickingInfo = result;
  14509. if (fastCheck) {
  14510. break;
  14511. }
  14512. }
  14513. return pickingInfo || new BABYLON.PickingInfo();
  14514. };
  14515. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14516. var pickingInfo = null;
  14517. camera = camera || this.activeCamera;
  14518. if (this.spriteManagers.length > 0) {
  14519. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14520. var spriteManager = this.spriteManagers[spriteIndex];
  14521. if (!spriteManager.isPickable) {
  14522. continue;
  14523. }
  14524. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14525. if (!result || !result.hit)
  14526. continue;
  14527. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14528. continue;
  14529. pickingInfo = result;
  14530. if (fastCheck) {
  14531. break;
  14532. }
  14533. }
  14534. }
  14535. return pickingInfo || new BABYLON.PickingInfo();
  14536. };
  14537. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14538. var _this = this;
  14539. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14540. /// <param name="x">X position on screen</param>
  14541. /// <param name="y">Y position on screen</param>
  14542. /// <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>
  14543. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14544. /// <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>
  14545. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14546. };
  14547. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14548. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14549. /// <param name="x">X position on screen</param>
  14550. /// <param name="y">Y position on screen</param>
  14551. /// <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>
  14552. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14553. /// <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>
  14554. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14555. };
  14556. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14557. var _this = this;
  14558. return this._internalPick(function (world) {
  14559. if (!_this._pickWithRayInverseMatrix) {
  14560. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14561. }
  14562. world.invertToRef(_this._pickWithRayInverseMatrix);
  14563. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14564. }, predicate, fastCheck);
  14565. };
  14566. Scene.prototype.setPointerOverMesh = function (mesh) {
  14567. if (this._pointerOverMesh === mesh) {
  14568. return;
  14569. }
  14570. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14571. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14572. }
  14573. this._pointerOverMesh = mesh;
  14574. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14575. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14576. }
  14577. };
  14578. Scene.prototype.getPointerOverMesh = function () {
  14579. return this._pointerOverMesh;
  14580. };
  14581. Scene.prototype.setPointerOverSprite = function (sprite) {
  14582. if (this._pointerOverSprite === sprite) {
  14583. return;
  14584. }
  14585. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14586. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14587. }
  14588. this._pointerOverSprite = sprite;
  14589. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14590. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14591. }
  14592. };
  14593. Scene.prototype.getPointerOverSprite = function () {
  14594. return this._pointerOverSprite;
  14595. };
  14596. // Physics
  14597. Scene.prototype.getPhysicsEngine = function () {
  14598. return this._physicsEngine;
  14599. };
  14600. /**
  14601. * Enables physics to the current scene
  14602. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14603. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14604. * @return {boolean} was the physics engine initialized
  14605. */
  14606. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14607. if (this._physicsEngine) {
  14608. return true;
  14609. }
  14610. try {
  14611. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  14612. return true;
  14613. }
  14614. catch (e) {
  14615. BABYLON.Tools.Error(e.message);
  14616. return false;
  14617. }
  14618. };
  14619. Scene.prototype.disablePhysicsEngine = function () {
  14620. if (!this._physicsEngine) {
  14621. return;
  14622. }
  14623. this._physicsEngine.dispose();
  14624. this._physicsEngine = undefined;
  14625. };
  14626. Scene.prototype.isPhysicsEnabled = function () {
  14627. return this._physicsEngine !== undefined;
  14628. };
  14629. /**
  14630. *
  14631. * Sets the gravity of the physics engine (and NOT of the scene)
  14632. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14633. */
  14634. Scene.prototype.setGravity = function (gravity) {
  14635. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  14636. if (!this._physicsEngine) {
  14637. return;
  14638. }
  14639. this._physicsEngine.setGravity(gravity);
  14640. };
  14641. /**
  14642. * Legacy support, using the new API
  14643. * @Deprecated
  14644. */
  14645. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14646. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  14647. if (parts.parts) {
  14648. options = parts;
  14649. parts = parts.parts;
  14650. }
  14651. var mainMesh = parts[0].mesh;
  14652. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options);
  14653. for (var index = 1; index < parts.length; index++) {
  14654. var mesh = parts[index].mesh;
  14655. if (mesh.parent !== mainMesh) {
  14656. mesh.position = mesh.position.subtract(mainMesh.position);
  14657. mesh.parent = mainMesh;
  14658. }
  14659. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options);
  14660. }
  14661. mainMesh.physicsImpostor.forceUpdate();
  14662. };
  14663. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14664. var mesh = compound.parts[0].mesh;
  14665. mesh.physicsImpostor.dispose(true);
  14666. mesh.physicsImpostor = null;
  14667. };
  14668. // Misc.
  14669. Scene.prototype.createDefaultCameraOrLight = function () {
  14670. // Light
  14671. if (this.lights.length === 0) {
  14672. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14673. }
  14674. // Camera
  14675. if (!this.activeCamera) {
  14676. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14677. // Compute position
  14678. var worldExtends = this.getWorldExtends();
  14679. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14680. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14681. camera.setTarget(worldCenter);
  14682. this.activeCamera = camera;
  14683. }
  14684. };
  14685. // Tags
  14686. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14687. if (tagsQuery === undefined) {
  14688. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14689. return list;
  14690. }
  14691. var listByTags = [];
  14692. forEach = forEach || (function (item) { return; });
  14693. for (var i in list) {
  14694. var item = list[i];
  14695. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14696. listByTags.push(item);
  14697. forEach(item);
  14698. }
  14699. }
  14700. return listByTags;
  14701. };
  14702. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14703. return this._getByTags(this.meshes, tagsQuery, forEach);
  14704. };
  14705. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14706. return this._getByTags(this.cameras, tagsQuery, forEach);
  14707. };
  14708. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14709. return this._getByTags(this.lights, tagsQuery, forEach);
  14710. };
  14711. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14712. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14713. };
  14714. // Statics
  14715. Scene._FOGMODE_NONE = 0;
  14716. Scene._FOGMODE_EXP = 1;
  14717. Scene._FOGMODE_EXP2 = 2;
  14718. Scene._FOGMODE_LINEAR = 3;
  14719. Scene.MinDeltaTime = 1.0;
  14720. Scene.MaxDeltaTime = 1000.0;
  14721. return Scene;
  14722. })();
  14723. BABYLON.Scene = Scene;
  14724. })(BABYLON || (BABYLON = {}));
  14725. var BABYLON;
  14726. (function (BABYLON) {
  14727. var VertexBuffer = (function () {
  14728. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14729. if (engine instanceof BABYLON.Mesh) {
  14730. this._engine = engine.getScene().getEngine();
  14731. }
  14732. else {
  14733. this._engine = engine;
  14734. }
  14735. this._updatable = updatable;
  14736. this._data = data;
  14737. if (!postponeInternalCreation) {
  14738. this.create();
  14739. }
  14740. this._kind = kind;
  14741. if (stride) {
  14742. this._strideSize = stride;
  14743. return;
  14744. }
  14745. // Deduce stride from kind
  14746. switch (kind) {
  14747. case VertexBuffer.PositionKind:
  14748. this._strideSize = 3;
  14749. break;
  14750. case VertexBuffer.NormalKind:
  14751. this._strideSize = 3;
  14752. break;
  14753. case VertexBuffer.UVKind:
  14754. case VertexBuffer.UV2Kind:
  14755. case VertexBuffer.UV3Kind:
  14756. case VertexBuffer.UV4Kind:
  14757. case VertexBuffer.UV5Kind:
  14758. case VertexBuffer.UV6Kind:
  14759. this._strideSize = 2;
  14760. break;
  14761. case VertexBuffer.ColorKind:
  14762. this._strideSize = 4;
  14763. break;
  14764. case VertexBuffer.MatricesIndicesKind:
  14765. case VertexBuffer.MatricesIndicesExtraKind:
  14766. this._strideSize = 4;
  14767. break;
  14768. case VertexBuffer.MatricesWeightsKind:
  14769. case VertexBuffer.MatricesWeightsExtraKind:
  14770. this._strideSize = 4;
  14771. break;
  14772. }
  14773. }
  14774. // Properties
  14775. VertexBuffer.prototype.isUpdatable = function () {
  14776. return this._updatable;
  14777. };
  14778. VertexBuffer.prototype.getData = function () {
  14779. return this._data;
  14780. };
  14781. VertexBuffer.prototype.getBuffer = function () {
  14782. return this._buffer;
  14783. };
  14784. VertexBuffer.prototype.getStrideSize = function () {
  14785. return this._strideSize;
  14786. };
  14787. // Methods
  14788. VertexBuffer.prototype.create = function (data) {
  14789. if (!data && this._buffer) {
  14790. return; // nothing to do
  14791. }
  14792. data = data || this._data;
  14793. if (!this._buffer) {
  14794. if (this._updatable) {
  14795. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14796. }
  14797. else {
  14798. this._buffer = this._engine.createVertexBuffer(data);
  14799. }
  14800. }
  14801. if (this._updatable) {
  14802. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14803. this._data = data;
  14804. }
  14805. };
  14806. VertexBuffer.prototype.update = function (data) {
  14807. this.create(data);
  14808. };
  14809. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14810. if (!this._buffer) {
  14811. return;
  14812. }
  14813. if (this._updatable) {
  14814. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14815. this._data = null;
  14816. }
  14817. };
  14818. VertexBuffer.prototype.dispose = function () {
  14819. if (!this._buffer) {
  14820. return;
  14821. }
  14822. if (this._engine._releaseBuffer(this._buffer)) {
  14823. this._buffer = null;
  14824. }
  14825. };
  14826. Object.defineProperty(VertexBuffer, "PositionKind", {
  14827. get: function () {
  14828. return VertexBuffer._PositionKind;
  14829. },
  14830. enumerable: true,
  14831. configurable: true
  14832. });
  14833. Object.defineProperty(VertexBuffer, "NormalKind", {
  14834. get: function () {
  14835. return VertexBuffer._NormalKind;
  14836. },
  14837. enumerable: true,
  14838. configurable: true
  14839. });
  14840. Object.defineProperty(VertexBuffer, "UVKind", {
  14841. get: function () {
  14842. return VertexBuffer._UVKind;
  14843. },
  14844. enumerable: true,
  14845. configurable: true
  14846. });
  14847. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14848. get: function () {
  14849. return VertexBuffer._UV2Kind;
  14850. },
  14851. enumerable: true,
  14852. configurable: true
  14853. });
  14854. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14855. get: function () {
  14856. return VertexBuffer._UV3Kind;
  14857. },
  14858. enumerable: true,
  14859. configurable: true
  14860. });
  14861. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14862. get: function () {
  14863. return VertexBuffer._UV4Kind;
  14864. },
  14865. enumerable: true,
  14866. configurable: true
  14867. });
  14868. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14869. get: function () {
  14870. return VertexBuffer._UV5Kind;
  14871. },
  14872. enumerable: true,
  14873. configurable: true
  14874. });
  14875. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14876. get: function () {
  14877. return VertexBuffer._UV6Kind;
  14878. },
  14879. enumerable: true,
  14880. configurable: true
  14881. });
  14882. Object.defineProperty(VertexBuffer, "ColorKind", {
  14883. get: function () {
  14884. return VertexBuffer._ColorKind;
  14885. },
  14886. enumerable: true,
  14887. configurable: true
  14888. });
  14889. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14890. get: function () {
  14891. return VertexBuffer._MatricesIndicesKind;
  14892. },
  14893. enumerable: true,
  14894. configurable: true
  14895. });
  14896. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14897. get: function () {
  14898. return VertexBuffer._MatricesWeightsKind;
  14899. },
  14900. enumerable: true,
  14901. configurable: true
  14902. });
  14903. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14904. get: function () {
  14905. return VertexBuffer._MatricesIndicesExtraKind;
  14906. },
  14907. enumerable: true,
  14908. configurable: true
  14909. });
  14910. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14911. get: function () {
  14912. return VertexBuffer._MatricesWeightsExtraKind;
  14913. },
  14914. enumerable: true,
  14915. configurable: true
  14916. });
  14917. // Enums
  14918. VertexBuffer._PositionKind = "position";
  14919. VertexBuffer._NormalKind = "normal";
  14920. VertexBuffer._UVKind = "uv";
  14921. VertexBuffer._UV2Kind = "uv2";
  14922. VertexBuffer._UV3Kind = "uv3";
  14923. VertexBuffer._UV4Kind = "uv4";
  14924. VertexBuffer._UV5Kind = "uv5";
  14925. VertexBuffer._UV6Kind = "uv6";
  14926. VertexBuffer._ColorKind = "color";
  14927. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14928. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14929. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14930. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14931. return VertexBuffer;
  14932. })();
  14933. BABYLON.VertexBuffer = VertexBuffer;
  14934. })(BABYLON || (BABYLON = {}));
  14935. var BABYLON;
  14936. (function (BABYLON) {
  14937. /**
  14938. * Creates an instance based on a source mesh.
  14939. */
  14940. var InstancedMesh = (function (_super) {
  14941. __extends(InstancedMesh, _super);
  14942. function InstancedMesh(name, source) {
  14943. _super.call(this, name, source.getScene());
  14944. source.instances.push(this);
  14945. this._sourceMesh = source;
  14946. this.position.copyFrom(source.position);
  14947. this.rotation.copyFrom(source.rotation);
  14948. this.scaling.copyFrom(source.scaling);
  14949. if (source.rotationQuaternion) {
  14950. this.rotationQuaternion = source.rotationQuaternion.clone();
  14951. }
  14952. this.infiniteDistance = source.infiniteDistance;
  14953. this.setPivotMatrix(source.getPivotMatrix());
  14954. this.refreshBoundingInfo();
  14955. this._syncSubMeshes();
  14956. }
  14957. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14958. // Methods
  14959. get: function () {
  14960. return this._sourceMesh.receiveShadows;
  14961. },
  14962. enumerable: true,
  14963. configurable: true
  14964. });
  14965. Object.defineProperty(InstancedMesh.prototype, "material", {
  14966. get: function () {
  14967. return this._sourceMesh.material;
  14968. },
  14969. enumerable: true,
  14970. configurable: true
  14971. });
  14972. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14973. get: function () {
  14974. return this._sourceMesh.visibility;
  14975. },
  14976. enumerable: true,
  14977. configurable: true
  14978. });
  14979. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14980. get: function () {
  14981. return this._sourceMesh.skeleton;
  14982. },
  14983. enumerable: true,
  14984. configurable: true
  14985. });
  14986. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14987. get: function () {
  14988. return this._sourceMesh.renderingGroupId;
  14989. },
  14990. enumerable: true,
  14991. configurable: true
  14992. });
  14993. InstancedMesh.prototype.getTotalVertices = function () {
  14994. return this._sourceMesh.getTotalVertices();
  14995. };
  14996. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14997. get: function () {
  14998. return this._sourceMesh;
  14999. },
  15000. enumerable: true,
  15001. configurable: true
  15002. });
  15003. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15004. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  15005. };
  15006. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  15007. return this._sourceMesh.isVerticesDataPresent(kind);
  15008. };
  15009. InstancedMesh.prototype.getIndices = function () {
  15010. return this._sourceMesh.getIndices();
  15011. };
  15012. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  15013. get: function () {
  15014. return this._sourceMesh._positions;
  15015. },
  15016. enumerable: true,
  15017. configurable: true
  15018. });
  15019. InstancedMesh.prototype.refreshBoundingInfo = function () {
  15020. var meshBB = this._sourceMesh.getBoundingInfo();
  15021. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  15022. this._updateBoundingInfo();
  15023. };
  15024. InstancedMesh.prototype._preActivate = function () {
  15025. if (this._currentLOD) {
  15026. this._currentLOD._preActivate();
  15027. }
  15028. };
  15029. InstancedMesh.prototype._activate = function (renderId) {
  15030. if (this._currentLOD) {
  15031. this._currentLOD._registerInstanceForRenderId(this, renderId);
  15032. }
  15033. };
  15034. InstancedMesh.prototype.getLOD = function (camera) {
  15035. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  15036. if (this._currentLOD === this.sourceMesh) {
  15037. return this;
  15038. }
  15039. return this._currentLOD;
  15040. };
  15041. InstancedMesh.prototype._syncSubMeshes = function () {
  15042. this.releaseSubMeshes();
  15043. if (this._sourceMesh.subMeshes) {
  15044. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  15045. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  15046. }
  15047. }
  15048. };
  15049. InstancedMesh.prototype._generatePointsArray = function () {
  15050. return this._sourceMesh._generatePointsArray();
  15051. };
  15052. // Clone
  15053. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15054. var result = this._sourceMesh.createInstance(name);
  15055. // Deep copy
  15056. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  15057. // Bounding info
  15058. this.refreshBoundingInfo();
  15059. // Parent
  15060. if (newParent) {
  15061. result.parent = newParent;
  15062. }
  15063. if (!doNotCloneChildren) {
  15064. // Children
  15065. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15066. var mesh = this.getScene().meshes[index];
  15067. if (mesh.parent === this) {
  15068. mesh.clone(mesh.name, result);
  15069. }
  15070. }
  15071. }
  15072. result.computeWorldMatrix(true);
  15073. return result;
  15074. };
  15075. // Dispoe
  15076. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  15077. // Remove from mesh
  15078. var index = this._sourceMesh.instances.indexOf(this);
  15079. this._sourceMesh.instances.splice(index, 1);
  15080. _super.prototype.dispose.call(this, doNotRecurse);
  15081. };
  15082. return InstancedMesh;
  15083. })(BABYLON.AbstractMesh);
  15084. BABYLON.InstancedMesh = InstancedMesh;
  15085. })(BABYLON || (BABYLON = {}));
  15086. var BABYLON;
  15087. (function (BABYLON) {
  15088. var _InstancesBatch = (function () {
  15089. function _InstancesBatch() {
  15090. this.mustReturn = false;
  15091. this.visibleInstances = new Array();
  15092. this.renderSelf = new Array();
  15093. }
  15094. return _InstancesBatch;
  15095. })();
  15096. BABYLON._InstancesBatch = _InstancesBatch;
  15097. var Mesh = (function (_super) {
  15098. __extends(Mesh, _super);
  15099. /**
  15100. * @constructor
  15101. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  15102. * @param {Scene} scene - The scene to add this mesh to.
  15103. * @param {Node} parent - The parent of this mesh, if it has one
  15104. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  15105. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  15106. * When false, achieved by calling a clone(), also passing False.
  15107. * This will make creation of children, recursive.
  15108. */
  15109. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  15110. if (parent === void 0) { parent = null; }
  15111. _super.call(this, name, scene);
  15112. // Members
  15113. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15114. this.instances = new Array();
  15115. this._LODLevels = new Array();
  15116. this._onBeforeRenderCallbacks = new Array();
  15117. this._onAfterRenderCallbacks = new Array();
  15118. this._visibleInstances = {};
  15119. this._renderIdForInstances = new Array();
  15120. this._batchCache = new _InstancesBatch();
  15121. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  15122. this._sideOrientation = Mesh._DEFAULTSIDE;
  15123. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  15124. if (source) {
  15125. // Geometry
  15126. if (source._geometry) {
  15127. source._geometry.applyToMesh(this);
  15128. }
  15129. // Deep copy
  15130. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  15131. // Pivot
  15132. this.setPivotMatrix(source.getPivotMatrix());
  15133. this.id = name + "." + source.id;
  15134. // Material
  15135. this.material = source.material;
  15136. var index;
  15137. if (!doNotCloneChildren) {
  15138. // Children
  15139. for (index = 0; index < scene.meshes.length; index++) {
  15140. var mesh = scene.meshes[index];
  15141. if (mesh.parent === source) {
  15142. // doNotCloneChildren is always going to be False
  15143. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  15144. }
  15145. }
  15146. }
  15147. // Particles
  15148. for (index = 0; index < scene.particleSystems.length; index++) {
  15149. var system = scene.particleSystems[index];
  15150. if (system.emitter === source) {
  15151. system.clone(system.name, this);
  15152. }
  15153. }
  15154. this.computeWorldMatrix(true);
  15155. }
  15156. // Parent
  15157. if (parent !== null) {
  15158. this.parent = parent;
  15159. }
  15160. }
  15161. Object.defineProperty(Mesh, "FRONTSIDE", {
  15162. get: function () {
  15163. return Mesh._FRONTSIDE;
  15164. },
  15165. enumerable: true,
  15166. configurable: true
  15167. });
  15168. Object.defineProperty(Mesh, "BACKSIDE", {
  15169. get: function () {
  15170. return Mesh._BACKSIDE;
  15171. },
  15172. enumerable: true,
  15173. configurable: true
  15174. });
  15175. Object.defineProperty(Mesh, "DOUBLESIDE", {
  15176. get: function () {
  15177. return Mesh._DOUBLESIDE;
  15178. },
  15179. enumerable: true,
  15180. configurable: true
  15181. });
  15182. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  15183. get: function () {
  15184. return Mesh._DEFAULTSIDE;
  15185. },
  15186. enumerable: true,
  15187. configurable: true
  15188. });
  15189. Object.defineProperty(Mesh, "NO_CAP", {
  15190. get: function () {
  15191. return Mesh._NO_CAP;
  15192. },
  15193. enumerable: true,
  15194. configurable: true
  15195. });
  15196. Object.defineProperty(Mesh, "CAP_START", {
  15197. get: function () {
  15198. return Mesh._CAP_START;
  15199. },
  15200. enumerable: true,
  15201. configurable: true
  15202. });
  15203. Object.defineProperty(Mesh, "CAP_END", {
  15204. get: function () {
  15205. return Mesh._CAP_END;
  15206. },
  15207. enumerable: true,
  15208. configurable: true
  15209. });
  15210. Object.defineProperty(Mesh, "CAP_ALL", {
  15211. get: function () {
  15212. return Mesh._CAP_ALL;
  15213. },
  15214. enumerable: true,
  15215. configurable: true
  15216. });
  15217. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  15218. // Methods
  15219. get: function () {
  15220. return this._LODLevels.length > 0;
  15221. },
  15222. enumerable: true,
  15223. configurable: true
  15224. });
  15225. Mesh.prototype._sortLODLevels = function () {
  15226. this._LODLevels.sort(function (a, b) {
  15227. if (a.distance < b.distance) {
  15228. return 1;
  15229. }
  15230. if (a.distance > b.distance) {
  15231. return -1;
  15232. }
  15233. return 0;
  15234. });
  15235. };
  15236. /**
  15237. * Add a mesh as LOD level triggered at the given distance.
  15238. * @param {number} distance - the distance from the center of the object to show this level
  15239. * @param {Mesh} mesh - the mesh to be added as LOD level
  15240. * @return {Mesh} this mesh (for chaining)
  15241. */
  15242. Mesh.prototype.addLODLevel = function (distance, mesh) {
  15243. if (mesh && mesh._masterMesh) {
  15244. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  15245. return this;
  15246. }
  15247. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  15248. this._LODLevels.push(level);
  15249. if (mesh) {
  15250. mesh._masterMesh = this;
  15251. }
  15252. this._sortLODLevels();
  15253. return this;
  15254. };
  15255. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  15256. for (var index = 0; index < this._LODLevels.length; index++) {
  15257. var level = this._LODLevels[index];
  15258. if (level.distance === distance) {
  15259. return level.mesh;
  15260. }
  15261. }
  15262. return null;
  15263. };
  15264. /**
  15265. * Remove a mesh from the LOD array
  15266. * @param {Mesh} mesh - the mesh to be removed.
  15267. * @return {Mesh} this mesh (for chaining)
  15268. */
  15269. Mesh.prototype.removeLODLevel = function (mesh) {
  15270. for (var index = 0; index < this._LODLevels.length; index++) {
  15271. if (this._LODLevels[index].mesh === mesh) {
  15272. this._LODLevels.splice(index, 1);
  15273. if (mesh) {
  15274. mesh._masterMesh = null;
  15275. }
  15276. }
  15277. }
  15278. this._sortLODLevels();
  15279. return this;
  15280. };
  15281. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  15282. if (!this._LODLevels || this._LODLevels.length === 0) {
  15283. return this;
  15284. }
  15285. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  15286. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  15287. if (this.onLODLevelSelection) {
  15288. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  15289. }
  15290. return this;
  15291. }
  15292. for (var index = 0; index < this._LODLevels.length; index++) {
  15293. var level = this._LODLevels[index];
  15294. if (level.distance < distanceToCamera) {
  15295. if (level.mesh) {
  15296. level.mesh._preActivate();
  15297. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15298. }
  15299. if (this.onLODLevelSelection) {
  15300. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  15301. }
  15302. return level.mesh;
  15303. }
  15304. }
  15305. if (this.onLODLevelSelection) {
  15306. this.onLODLevelSelection(distanceToCamera, this, this);
  15307. }
  15308. return this;
  15309. };
  15310. Object.defineProperty(Mesh.prototype, "geometry", {
  15311. get: function () {
  15312. return this._geometry;
  15313. },
  15314. enumerable: true,
  15315. configurable: true
  15316. });
  15317. Mesh.prototype.getTotalVertices = function () {
  15318. if (!this._geometry) {
  15319. return 0;
  15320. }
  15321. return this._geometry.getTotalVertices();
  15322. };
  15323. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15324. if (!this._geometry) {
  15325. return null;
  15326. }
  15327. return this._geometry.getVerticesData(kind, copyWhenShared);
  15328. };
  15329. Mesh.prototype.getVertexBuffer = function (kind) {
  15330. if (!this._geometry) {
  15331. return undefined;
  15332. }
  15333. return this._geometry.getVertexBuffer(kind);
  15334. };
  15335. Mesh.prototype.isVerticesDataPresent = function (kind) {
  15336. if (!this._geometry) {
  15337. if (this._delayInfo) {
  15338. return this._delayInfo.indexOf(kind) !== -1;
  15339. }
  15340. return false;
  15341. }
  15342. return this._geometry.isVerticesDataPresent(kind);
  15343. };
  15344. Mesh.prototype.getVerticesDataKinds = function () {
  15345. if (!this._geometry) {
  15346. var result = [];
  15347. if (this._delayInfo) {
  15348. for (var kind in this._delayInfo) {
  15349. result.push(kind);
  15350. }
  15351. }
  15352. return result;
  15353. }
  15354. return this._geometry.getVerticesDataKinds();
  15355. };
  15356. Mesh.prototype.getTotalIndices = function () {
  15357. if (!this._geometry) {
  15358. return 0;
  15359. }
  15360. return this._geometry.getTotalIndices();
  15361. };
  15362. Mesh.prototype.getIndices = function (copyWhenShared) {
  15363. if (!this._geometry) {
  15364. return [];
  15365. }
  15366. return this._geometry.getIndices(copyWhenShared);
  15367. };
  15368. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15369. get: function () {
  15370. return this._masterMesh !== null && this._masterMesh !== undefined;
  15371. },
  15372. enumerable: true,
  15373. configurable: true
  15374. });
  15375. Mesh.prototype.isReady = function () {
  15376. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15377. return false;
  15378. }
  15379. return _super.prototype.isReady.call(this);
  15380. };
  15381. Mesh.prototype.isDisposed = function () {
  15382. return this._isDisposed;
  15383. };
  15384. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15385. get: function () {
  15386. return this._sideOrientation;
  15387. },
  15388. set: function (sideO) {
  15389. this._sideOrientation = sideO;
  15390. },
  15391. enumerable: true,
  15392. configurable: true
  15393. });
  15394. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15395. get: function () {
  15396. return this._areNormalsFrozen;
  15397. },
  15398. enumerable: true,
  15399. configurable: true
  15400. });
  15401. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15402. Mesh.prototype.freezeNormals = function () {
  15403. this._areNormalsFrozen = true;
  15404. };
  15405. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15406. Mesh.prototype.unfreezeNormals = function () {
  15407. this._areNormalsFrozen = false;
  15408. };
  15409. // Methods
  15410. Mesh.prototype._preActivate = function () {
  15411. var sceneRenderId = this.getScene().getRenderId();
  15412. if (this._preActivateId === sceneRenderId) {
  15413. return;
  15414. }
  15415. this._preActivateId = sceneRenderId;
  15416. this._visibleInstances = null;
  15417. };
  15418. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15419. if (!this._visibleInstances) {
  15420. this._visibleInstances = {};
  15421. this._visibleInstances.defaultRenderId = renderId;
  15422. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15423. }
  15424. if (!this._visibleInstances[renderId]) {
  15425. this._visibleInstances[renderId] = new Array();
  15426. }
  15427. this._visibleInstances[renderId].push(instance);
  15428. };
  15429. Mesh.prototype.refreshBoundingInfo = function () {
  15430. if (this._boundingInfo.isLocked) {
  15431. return;
  15432. }
  15433. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15434. if (data) {
  15435. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15436. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15437. }
  15438. if (this.subMeshes) {
  15439. for (var index = 0; index < this.subMeshes.length; index++) {
  15440. this.subMeshes[index].refreshBoundingInfo();
  15441. }
  15442. }
  15443. this._updateBoundingInfo();
  15444. };
  15445. Mesh.prototype._createGlobalSubMesh = function () {
  15446. var totalVertices = this.getTotalVertices();
  15447. if (!totalVertices || !this.getIndices()) {
  15448. return null;
  15449. }
  15450. this.releaseSubMeshes();
  15451. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15452. };
  15453. Mesh.prototype.subdivide = function (count) {
  15454. if (count < 1) {
  15455. return;
  15456. }
  15457. var totalIndices = this.getTotalIndices();
  15458. var subdivisionSize = (totalIndices / count) | 0;
  15459. var offset = 0;
  15460. // Ensure that subdivisionSize is a multiple of 3
  15461. while (subdivisionSize % 3 !== 0) {
  15462. subdivisionSize++;
  15463. }
  15464. this.releaseSubMeshes();
  15465. for (var index = 0; index < count; index++) {
  15466. if (offset >= totalIndices) {
  15467. break;
  15468. }
  15469. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15470. offset += subdivisionSize;
  15471. }
  15472. this.synchronizeInstances();
  15473. };
  15474. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15475. if (!this._geometry) {
  15476. var vertexData = new BABYLON.VertexData();
  15477. vertexData.set(data, kind);
  15478. var scene = this.getScene();
  15479. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15480. }
  15481. else {
  15482. this._geometry.setVerticesData(kind, data, updatable, stride);
  15483. }
  15484. };
  15485. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15486. if (!this._geometry) {
  15487. return;
  15488. }
  15489. if (!makeItUnique) {
  15490. this._geometry.updateVerticesData(kind, data, updateExtends);
  15491. }
  15492. else {
  15493. this.makeGeometryUnique();
  15494. this.updateVerticesData(kind, data, updateExtends, false);
  15495. }
  15496. };
  15497. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15498. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15499. if (!this._geometry) {
  15500. return;
  15501. }
  15502. if (!makeItUnique) {
  15503. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15504. }
  15505. else {
  15506. this.makeGeometryUnique();
  15507. this.updateVerticesDataDirectly(kind, data, offset, false);
  15508. }
  15509. };
  15510. // Mesh positions update function :
  15511. // updates the mesh positions according to the positionFunction returned values.
  15512. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15513. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15514. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15515. if (computeNormals === void 0) { computeNormals = true; }
  15516. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15517. positionFunction(positions);
  15518. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15519. if (computeNormals) {
  15520. var indices = this.getIndices();
  15521. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15522. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15523. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15524. }
  15525. };
  15526. Mesh.prototype.makeGeometryUnique = function () {
  15527. if (!this._geometry) {
  15528. return;
  15529. }
  15530. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15531. geometry.applyToMesh(this);
  15532. };
  15533. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15534. if (!this._geometry) {
  15535. var vertexData = new BABYLON.VertexData();
  15536. vertexData.indices = indices;
  15537. var scene = this.getScene();
  15538. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15539. }
  15540. else {
  15541. this._geometry.setIndices(indices, totalVertices);
  15542. }
  15543. };
  15544. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15545. var engine = this.getScene().getEngine();
  15546. // Wireframe
  15547. var indexToBind;
  15548. if (this._unIndexed) {
  15549. indexToBind = null;
  15550. }
  15551. else {
  15552. switch (fillMode) {
  15553. case BABYLON.Material.PointFillMode:
  15554. indexToBind = null;
  15555. break;
  15556. case BABYLON.Material.WireFrameFillMode:
  15557. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15558. break;
  15559. default:
  15560. case BABYLON.Material.TriangleFillMode:
  15561. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15562. break;
  15563. }
  15564. }
  15565. // VBOs
  15566. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15567. };
  15568. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15569. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15570. return;
  15571. }
  15572. if (this.onBeforeDraw) {
  15573. this.onBeforeDraw();
  15574. }
  15575. var engine = this.getScene().getEngine();
  15576. // Draw order
  15577. switch (fillMode) {
  15578. case BABYLON.Material.PointFillMode:
  15579. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15580. break;
  15581. case BABYLON.Material.WireFrameFillMode:
  15582. if (this._unIndexed) {
  15583. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15584. }
  15585. else {
  15586. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15587. }
  15588. break;
  15589. default:
  15590. if (this._unIndexed) {
  15591. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15592. }
  15593. else {
  15594. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15595. }
  15596. }
  15597. };
  15598. Mesh.prototype.registerBeforeRender = function (func) {
  15599. this._onBeforeRenderCallbacks.push(func);
  15600. };
  15601. Mesh.prototype.unregisterBeforeRender = function (func) {
  15602. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15603. if (index > -1) {
  15604. this._onBeforeRenderCallbacks.splice(index, 1);
  15605. }
  15606. };
  15607. Mesh.prototype.registerAfterRender = function (func) {
  15608. this._onAfterRenderCallbacks.push(func);
  15609. };
  15610. Mesh.prototype.unregisterAfterRender = function (func) {
  15611. var index = this._onAfterRenderCallbacks.indexOf(func);
  15612. if (index > -1) {
  15613. this._onAfterRenderCallbacks.splice(index, 1);
  15614. }
  15615. };
  15616. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15617. var scene = this.getScene();
  15618. this._batchCache.mustReturn = false;
  15619. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15620. this._batchCache.visibleInstances[subMeshId] = null;
  15621. if (this._visibleInstances) {
  15622. var currentRenderId = scene.getRenderId();
  15623. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15624. var selfRenderId = this._renderId;
  15625. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15626. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15627. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15628. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15629. }
  15630. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15631. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15632. this._batchCache.mustReturn = true;
  15633. return this._batchCache;
  15634. }
  15635. if (currentRenderId !== selfRenderId) {
  15636. this._batchCache.renderSelf[subMeshId] = false;
  15637. }
  15638. }
  15639. this._renderIdForInstances[subMeshId] = currentRenderId;
  15640. }
  15641. return this._batchCache;
  15642. };
  15643. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15644. var visibleInstances = batch.visibleInstances[subMesh._id];
  15645. var matricesCount = visibleInstances.length + 1;
  15646. var bufferSize = matricesCount * 16 * 4;
  15647. while (this._instancesBufferSize < bufferSize) {
  15648. this._instancesBufferSize *= 2;
  15649. }
  15650. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15651. if (this._worldMatricesInstancesBuffer) {
  15652. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15653. }
  15654. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15655. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15656. }
  15657. var offset = 0;
  15658. var instancesCount = 0;
  15659. var world = this.getWorldMatrix();
  15660. if (batch.renderSelf[subMesh._id]) {
  15661. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15662. offset += 16;
  15663. instancesCount++;
  15664. }
  15665. if (visibleInstances) {
  15666. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15667. var instance = visibleInstances[instanceIndex];
  15668. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15669. offset += 16;
  15670. instancesCount++;
  15671. }
  15672. }
  15673. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15674. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15675. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15676. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15677. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15678. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15679. this._draw(subMesh, fillMode, instancesCount);
  15680. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15681. };
  15682. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15683. var scene = this.getScene();
  15684. var engine = scene.getEngine();
  15685. if (hardwareInstancedRendering) {
  15686. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15687. }
  15688. else {
  15689. if (batch.renderSelf[subMesh._id]) {
  15690. // Draw
  15691. if (onBeforeDraw) {
  15692. onBeforeDraw(false, this.getWorldMatrix());
  15693. }
  15694. this._draw(subMesh, fillMode);
  15695. }
  15696. if (batch.visibleInstances[subMesh._id]) {
  15697. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15698. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15699. // World
  15700. var world = instance.getWorldMatrix();
  15701. if (onBeforeDraw) {
  15702. onBeforeDraw(true, world);
  15703. }
  15704. // Draw
  15705. this._draw(subMesh, fillMode);
  15706. }
  15707. }
  15708. }
  15709. };
  15710. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15711. var scene = this.getScene();
  15712. // Managing instances
  15713. var batch = this._getInstancesRenderList(subMesh._id);
  15714. if (batch.mustReturn) {
  15715. return;
  15716. }
  15717. // Checking geometry state
  15718. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15719. return;
  15720. }
  15721. var callbackIndex;
  15722. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15723. this._onBeforeRenderCallbacks[callbackIndex](this);
  15724. }
  15725. var engine = scene.getEngine();
  15726. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15727. // Material
  15728. var effectiveMaterial = subMesh.getMaterial();
  15729. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15730. return;
  15731. }
  15732. // Outline - step 1
  15733. var savedDepthWrite = engine.getDepthWrite();
  15734. if (this.renderOutline) {
  15735. engine.setDepthWrite(false);
  15736. scene.getOutlineRenderer().render(subMesh, batch);
  15737. engine.setDepthWrite(savedDepthWrite);
  15738. }
  15739. effectiveMaterial._preBind();
  15740. var effect = effectiveMaterial.getEffect();
  15741. // Bind
  15742. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15743. this._bind(subMesh, effect, fillMode);
  15744. var world = this.getWorldMatrix();
  15745. effectiveMaterial.bind(world, this);
  15746. // Alpha mode
  15747. if (enableAlphaMode) {
  15748. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15749. }
  15750. // Draw
  15751. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15752. if (isInstance) {
  15753. effectiveMaterial.bindOnlyWorldMatrix(world);
  15754. }
  15755. });
  15756. // Unbind
  15757. effectiveMaterial.unbind();
  15758. // Outline - step 2
  15759. if (this.renderOutline && savedDepthWrite) {
  15760. engine.setDepthWrite(true);
  15761. engine.setColorWrite(false);
  15762. scene.getOutlineRenderer().render(subMesh, batch);
  15763. engine.setColorWrite(true);
  15764. }
  15765. // Overlay
  15766. if (this.renderOverlay) {
  15767. var currentMode = engine.getAlphaMode();
  15768. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15769. scene.getOutlineRenderer().render(subMesh, batch, true);
  15770. engine.setAlphaMode(currentMode);
  15771. }
  15772. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15773. this._onAfterRenderCallbacks[callbackIndex](this);
  15774. }
  15775. };
  15776. Mesh.prototype.getEmittedParticleSystems = function () {
  15777. var results = new Array();
  15778. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15779. var particleSystem = this.getScene().particleSystems[index];
  15780. if (particleSystem.emitter === this) {
  15781. results.push(particleSystem);
  15782. }
  15783. }
  15784. return results;
  15785. };
  15786. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15787. var results = new Array();
  15788. var descendants = this.getDescendants();
  15789. descendants.push(this);
  15790. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15791. var particleSystem = this.getScene().particleSystems[index];
  15792. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15793. results.push(particleSystem);
  15794. }
  15795. }
  15796. return results;
  15797. };
  15798. Mesh.prototype._checkDelayState = function () {
  15799. var _this = this;
  15800. var that = this;
  15801. var scene = this.getScene();
  15802. if (this._geometry) {
  15803. this._geometry.load(scene);
  15804. }
  15805. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15806. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15807. scene._addPendingData(that);
  15808. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15809. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15810. if (data instanceof ArrayBuffer) {
  15811. _this._delayLoadingFunction(data, _this);
  15812. }
  15813. else {
  15814. _this._delayLoadingFunction(JSON.parse(data), _this);
  15815. }
  15816. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15817. scene._removePendingData(_this);
  15818. }, function () { }, scene.database, getBinaryData);
  15819. }
  15820. };
  15821. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15822. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15823. return false;
  15824. }
  15825. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15826. return false;
  15827. }
  15828. this._checkDelayState();
  15829. return true;
  15830. };
  15831. Mesh.prototype.setMaterialByID = function (id) {
  15832. var materials = this.getScene().materials;
  15833. var index;
  15834. for (index = 0; index < materials.length; index++) {
  15835. if (materials[index].id === id) {
  15836. this.material = materials[index];
  15837. return;
  15838. }
  15839. }
  15840. // Multi
  15841. var multiMaterials = this.getScene().multiMaterials;
  15842. for (index = 0; index < multiMaterials.length; index++) {
  15843. if (multiMaterials[index].id === id) {
  15844. this.material = multiMaterials[index];
  15845. return;
  15846. }
  15847. }
  15848. };
  15849. Mesh.prototype.getAnimatables = function () {
  15850. var results = [];
  15851. if (this.material) {
  15852. results.push(this.material);
  15853. }
  15854. if (this.skeleton) {
  15855. results.push(this.skeleton);
  15856. }
  15857. return results;
  15858. };
  15859. // Geometry
  15860. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15861. // Position
  15862. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15863. return;
  15864. }
  15865. this._resetPointsArrayCache();
  15866. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15867. var temp = [];
  15868. var index;
  15869. for (index = 0; index < data.length; index += 3) {
  15870. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15871. }
  15872. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15873. // Normals
  15874. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15875. return;
  15876. }
  15877. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15878. temp = [];
  15879. for (index = 0; index < data.length; index += 3) {
  15880. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15881. }
  15882. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15883. // flip faces?
  15884. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15885. this.flipFaces();
  15886. }
  15887. };
  15888. // Will apply current transform to mesh and reset world matrix
  15889. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15890. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15891. this.scaling.copyFromFloats(1, 1, 1);
  15892. this.position.copyFromFloats(0, 0, 0);
  15893. this.rotation.copyFromFloats(0, 0, 0);
  15894. //only if quaternion is already set
  15895. if (this.rotationQuaternion) {
  15896. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15897. }
  15898. this._worldMatrix = BABYLON.Matrix.Identity();
  15899. };
  15900. // Cache
  15901. Mesh.prototype._resetPointsArrayCache = function () {
  15902. this._positions = null;
  15903. };
  15904. Mesh.prototype._generatePointsArray = function () {
  15905. if (this._positions)
  15906. return true;
  15907. this._positions = [];
  15908. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15909. if (!data) {
  15910. return false;
  15911. }
  15912. for (var index = 0; index < data.length; index += 3) {
  15913. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15914. }
  15915. return true;
  15916. };
  15917. // Clone
  15918. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15919. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15920. };
  15921. // Dispose
  15922. Mesh.prototype.dispose = function (doNotRecurse) {
  15923. if (this._geometry) {
  15924. this._geometry.releaseForMesh(this, true);
  15925. }
  15926. // Instances
  15927. if (this._worldMatricesInstancesBuffer) {
  15928. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15929. this._worldMatricesInstancesBuffer = null;
  15930. }
  15931. while (this.instances.length) {
  15932. this.instances[0].dispose();
  15933. }
  15934. _super.prototype.dispose.call(this, doNotRecurse);
  15935. };
  15936. // Geometric tools
  15937. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15938. var _this = this;
  15939. var scene = this.getScene();
  15940. var onload = function (img) {
  15941. // Getting height map data
  15942. var canvas = document.createElement("canvas");
  15943. var context = canvas.getContext("2d");
  15944. var heightMapWidth = img.width;
  15945. var heightMapHeight = img.height;
  15946. canvas.width = heightMapWidth;
  15947. canvas.height = heightMapHeight;
  15948. context.drawImage(img, 0, 0);
  15949. // Create VertexData from map data
  15950. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15951. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15952. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15953. //execute success callback, if set
  15954. if (onSuccess) {
  15955. onSuccess(_this);
  15956. }
  15957. };
  15958. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15959. };
  15960. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15961. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15962. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15963. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15964. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15965. return;
  15966. }
  15967. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15968. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15969. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15970. var position = BABYLON.Vector3.Zero();
  15971. var normal = BABYLON.Vector3.Zero();
  15972. var uv = BABYLON.Vector2.Zero();
  15973. for (var index = 0; index < positions.length; index += 3) {
  15974. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15975. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15976. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15977. // Compute height
  15978. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15979. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15980. var pos = (u + v * heightMapWidth) * 4;
  15981. var r = buffer[pos] / 255.0;
  15982. var g = buffer[pos + 1] / 255.0;
  15983. var b = buffer[pos + 2] / 255.0;
  15984. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15985. normal.normalize();
  15986. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15987. position = position.add(normal);
  15988. position.toArray(positions, index);
  15989. }
  15990. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15991. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15992. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15993. };
  15994. Mesh.prototype.convertToFlatShadedMesh = function () {
  15995. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15996. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15997. var kinds = this.getVerticesDataKinds();
  15998. var vbs = [];
  15999. var data = [];
  16000. var newdata = [];
  16001. var updatableNormals = false;
  16002. var kindIndex;
  16003. var kind;
  16004. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16005. kind = kinds[kindIndex];
  16006. var vertexBuffer = this.getVertexBuffer(kind);
  16007. if (kind === BABYLON.VertexBuffer.NormalKind) {
  16008. updatableNormals = vertexBuffer.isUpdatable();
  16009. kinds.splice(kindIndex, 1);
  16010. kindIndex--;
  16011. continue;
  16012. }
  16013. vbs[kind] = vertexBuffer;
  16014. data[kind] = vbs[kind].getData();
  16015. newdata[kind] = [];
  16016. }
  16017. // Save previous submeshes
  16018. var previousSubmeshes = this.subMeshes.slice(0);
  16019. var indices = this.getIndices();
  16020. var totalIndices = this.getTotalIndices();
  16021. // Generating unique vertices per face
  16022. var index;
  16023. for (index = 0; index < totalIndices; index++) {
  16024. var vertexIndex = indices[index];
  16025. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16026. kind = kinds[kindIndex];
  16027. var stride = vbs[kind].getStrideSize();
  16028. for (var offset = 0; offset < stride; offset++) {
  16029. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16030. }
  16031. }
  16032. }
  16033. // Updating faces & normal
  16034. var normals = [];
  16035. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  16036. for (index = 0; index < totalIndices; index += 3) {
  16037. indices[index] = index;
  16038. indices[index + 1] = index + 1;
  16039. indices[index + 2] = index + 2;
  16040. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  16041. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  16042. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  16043. var p1p2 = p1.subtract(p2);
  16044. var p3p2 = p3.subtract(p2);
  16045. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  16046. // Store same normals for every vertex
  16047. for (var localIndex = 0; localIndex < 3; localIndex++) {
  16048. normals.push(normal.x);
  16049. normals.push(normal.y);
  16050. normals.push(normal.z);
  16051. }
  16052. }
  16053. this.setIndices(indices);
  16054. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  16055. // Updating vertex buffers
  16056. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16057. kind = kinds[kindIndex];
  16058. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16059. }
  16060. // Updating submeshes
  16061. this.releaseSubMeshes();
  16062. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16063. var previousOne = previousSubmeshes[submeshIndex];
  16064. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16065. }
  16066. this.synchronizeInstances();
  16067. };
  16068. Mesh.prototype.convertToUnIndexedMesh = function () {
  16069. /// <summary>Remove indices by unfolding faces into buffers</summary>
  16070. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  16071. var kinds = this.getVerticesDataKinds();
  16072. var vbs = [];
  16073. var data = [];
  16074. var newdata = [];
  16075. var updatableNormals = false;
  16076. var kindIndex;
  16077. var kind;
  16078. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16079. kind = kinds[kindIndex];
  16080. var vertexBuffer = this.getVertexBuffer(kind);
  16081. vbs[kind] = vertexBuffer;
  16082. data[kind] = vbs[kind].getData();
  16083. newdata[kind] = [];
  16084. }
  16085. // Save previous submeshes
  16086. var previousSubmeshes = this.subMeshes.slice(0);
  16087. var indices = this.getIndices();
  16088. var totalIndices = this.getTotalIndices();
  16089. // Generating unique vertices per face
  16090. var index;
  16091. for (index = 0; index < totalIndices; index++) {
  16092. var vertexIndex = indices[index];
  16093. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16094. kind = kinds[kindIndex];
  16095. var stride = vbs[kind].getStrideSize();
  16096. for (var offset = 0; offset < stride; offset++) {
  16097. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16098. }
  16099. }
  16100. }
  16101. // Updating indices
  16102. for (index = 0; index < totalIndices; index += 3) {
  16103. indices[index] = index;
  16104. indices[index + 1] = index + 1;
  16105. indices[index + 2] = index + 2;
  16106. }
  16107. this.setIndices(indices);
  16108. // Updating vertex buffers
  16109. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16110. kind = kinds[kindIndex];
  16111. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16112. }
  16113. // Updating submeshes
  16114. this.releaseSubMeshes();
  16115. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16116. var previousOne = previousSubmeshes[submeshIndex];
  16117. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16118. }
  16119. this._unIndexed = true;
  16120. this.synchronizeInstances();
  16121. };
  16122. // will inverse faces orientations, and invert normals too if specified
  16123. Mesh.prototype.flipFaces = function (flipNormals) {
  16124. if (flipNormals === void 0) { flipNormals = false; }
  16125. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  16126. var i;
  16127. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16128. for (i = 0; i < vertex_data.normals.length; i++) {
  16129. vertex_data.normals[i] *= -1;
  16130. }
  16131. }
  16132. var temp;
  16133. for (i = 0; i < vertex_data.indices.length; i += 3) {
  16134. // reassign indices
  16135. temp = vertex_data.indices[i + 1];
  16136. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  16137. vertex_data.indices[i + 2] = temp;
  16138. }
  16139. vertex_data.applyToMesh(this);
  16140. };
  16141. // Instances
  16142. Mesh.prototype.createInstance = function (name) {
  16143. return new BABYLON.InstancedMesh(name, this);
  16144. };
  16145. Mesh.prototype.synchronizeInstances = function () {
  16146. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  16147. var instance = this.instances[instanceIndex];
  16148. instance._syncSubMeshes();
  16149. }
  16150. };
  16151. /**
  16152. * Simplify the mesh according to the given array of settings.
  16153. * Function will return immediately and will simplify async.
  16154. * @param settings a collection of simplification settings.
  16155. * @param parallelProcessing should all levels calculate parallel or one after the other.
  16156. * @param type the type of simplification to run.
  16157. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  16158. */
  16159. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  16160. if (parallelProcessing === void 0) { parallelProcessing = true; }
  16161. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  16162. this.getScene().simplificationQueue.addTask({
  16163. settings: settings,
  16164. parallelProcessing: parallelProcessing,
  16165. mesh: this,
  16166. simplificationType: simplificationType,
  16167. successCallback: successCallback
  16168. });
  16169. };
  16170. /**
  16171. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  16172. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  16173. * This should be used together with the simplification to avoid disappearing triangles.
  16174. * @param successCallback an optional success callback to be called after the optimization finished.
  16175. */
  16176. Mesh.prototype.optimizeIndices = function (successCallback) {
  16177. var _this = this;
  16178. var indices = this.getIndices();
  16179. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16180. var vectorPositions = [];
  16181. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  16182. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  16183. }
  16184. var dupes = [];
  16185. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  16186. var realPos = vectorPositions.length - 1 - iteration;
  16187. var testedPosition = vectorPositions[realPos];
  16188. for (var j = 0; j < realPos; ++j) {
  16189. var againstPosition = vectorPositions[j];
  16190. if (testedPosition.equals(againstPosition)) {
  16191. dupes[realPos] = j;
  16192. break;
  16193. }
  16194. }
  16195. }, function () {
  16196. for (var i = 0; i < indices.length; ++i) {
  16197. indices[i] = dupes[indices[i]] || indices[i];
  16198. }
  16199. //indices are now reordered
  16200. var originalSubMeshes = _this.subMeshes.slice(0);
  16201. _this.setIndices(indices);
  16202. _this.subMeshes = originalSubMeshes;
  16203. if (successCallback) {
  16204. successCallback(_this);
  16205. }
  16206. });
  16207. };
  16208. // Statics
  16209. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  16210. var mesh = new Mesh(parsedMesh.name, scene);
  16211. mesh.id = parsedMesh.id;
  16212. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16213. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16214. if (parsedMesh.rotationQuaternion) {
  16215. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16216. }
  16217. else if (parsedMesh.rotation) {
  16218. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16219. }
  16220. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16221. if (parsedMesh.localMatrix) {
  16222. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16223. }
  16224. else if (parsedMesh.pivotMatrix) {
  16225. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16226. }
  16227. mesh.setEnabled(parsedMesh.isEnabled);
  16228. mesh.isVisible = parsedMesh.isVisible;
  16229. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16230. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16231. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16232. if (parsedMesh.applyFog !== undefined) {
  16233. mesh.applyFog = parsedMesh.applyFog;
  16234. }
  16235. if (parsedMesh.pickable !== undefined) {
  16236. mesh.isPickable = parsedMesh.pickable;
  16237. }
  16238. if (parsedMesh.alphaIndex !== undefined) {
  16239. mesh.alphaIndex = parsedMesh.alphaIndex;
  16240. }
  16241. mesh.receiveShadows = parsedMesh.receiveShadows;
  16242. mesh.billboardMode = parsedMesh.billboardMode;
  16243. if (parsedMesh.visibility !== undefined) {
  16244. mesh.visibility = parsedMesh.visibility;
  16245. }
  16246. mesh.checkCollisions = parsedMesh.checkCollisions;
  16247. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16248. // freezeWorldMatrix
  16249. if (parsedMesh.freezeWorldMatrix) {
  16250. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  16251. }
  16252. // Parent
  16253. if (parsedMesh.parentId) {
  16254. mesh._waitingParentId = parsedMesh.parentId;
  16255. }
  16256. // Actions
  16257. if (parsedMesh.actions !== undefined) {
  16258. mesh._waitingActions = parsedMesh.actions;
  16259. }
  16260. // Geometry
  16261. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16262. if (parsedMesh.delayLoadingFile) {
  16263. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16264. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16265. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16266. if (parsedMesh._binaryInfo) {
  16267. mesh._binaryInfo = parsedMesh._binaryInfo;
  16268. }
  16269. mesh._delayInfo = [];
  16270. if (parsedMesh.hasUVs) {
  16271. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16272. }
  16273. if (parsedMesh.hasUVs2) {
  16274. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16275. }
  16276. if (parsedMesh.hasUVs3) {
  16277. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  16278. }
  16279. if (parsedMesh.hasUVs4) {
  16280. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  16281. }
  16282. if (parsedMesh.hasUVs5) {
  16283. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  16284. }
  16285. if (parsedMesh.hasUVs6) {
  16286. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  16287. }
  16288. if (parsedMesh.hasColors) {
  16289. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16290. }
  16291. if (parsedMesh.hasMatricesIndices) {
  16292. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16293. }
  16294. if (parsedMesh.hasMatricesWeights) {
  16295. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16296. }
  16297. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  16298. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16299. mesh._checkDelayState();
  16300. }
  16301. }
  16302. else {
  16303. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  16304. }
  16305. // Material
  16306. if (parsedMesh.materialId) {
  16307. mesh.setMaterialByID(parsedMesh.materialId);
  16308. }
  16309. else {
  16310. mesh.material = null;
  16311. }
  16312. // Skeleton
  16313. if (parsedMesh.skeletonId > -1) {
  16314. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16315. if (parsedMesh.numBoneInfluencers) {
  16316. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  16317. }
  16318. }
  16319. // Animations
  16320. if (parsedMesh.animations) {
  16321. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16322. var parsedAnimation = parsedMesh.animations[animationIndex];
  16323. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16324. }
  16325. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  16326. }
  16327. if (parsedMesh.autoAnimate) {
  16328. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  16329. }
  16330. // Layer Mask
  16331. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16332. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16333. }
  16334. else {
  16335. mesh.layerMask = 0x0FFFFFFF;
  16336. }
  16337. // Instances
  16338. if (parsedMesh.instances) {
  16339. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16340. var parsedInstance = parsedMesh.instances[index];
  16341. var instance = mesh.createInstance(parsedInstance.name);
  16342. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16343. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16344. if (parsedInstance.rotationQuaternion) {
  16345. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16346. }
  16347. else if (parsedInstance.rotation) {
  16348. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16349. }
  16350. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16351. instance.checkCollisions = mesh.checkCollisions;
  16352. if (parsedMesh.animations) {
  16353. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16354. parsedAnimation = parsedMesh.animations[animationIndex];
  16355. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16356. }
  16357. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16358. }
  16359. }
  16360. }
  16361. return mesh;
  16362. };
  16363. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16364. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16365. pathArray: pathArray,
  16366. closeArray: closeArray,
  16367. closePath: closePath,
  16368. offset: offset,
  16369. updatable: updatable,
  16370. sideOrientation: sideOrientation,
  16371. instance: instance
  16372. }, scene);
  16373. };
  16374. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16375. var options = {
  16376. radius: radius,
  16377. tessellation: tessellation,
  16378. sideOrientation: sideOrientation,
  16379. updatable: updatable
  16380. };
  16381. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16382. };
  16383. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16384. var options = {
  16385. size: size,
  16386. sideOrientation: sideOrientation,
  16387. updatable: updatable
  16388. };
  16389. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16390. };
  16391. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16392. var options = {
  16393. segments: segments,
  16394. diameterX: diameter,
  16395. diameterY: diameter,
  16396. diameterZ: diameter,
  16397. sideOrientation: sideOrientation,
  16398. updatable: updatable
  16399. };
  16400. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16401. };
  16402. // Cylinder and cone
  16403. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16404. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16405. if (scene !== undefined) {
  16406. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16407. updatable = scene;
  16408. }
  16409. scene = subdivisions;
  16410. subdivisions = 1;
  16411. }
  16412. var options = {
  16413. height: height,
  16414. diameterTop: diameterTop,
  16415. diameterBottom: diameterBottom,
  16416. tessellation: tessellation,
  16417. subdivisions: subdivisions,
  16418. sideOrientation: sideOrientation,
  16419. updatable: updatable
  16420. };
  16421. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16422. };
  16423. // Torus (Code from SharpDX.org)
  16424. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16425. var options = {
  16426. diameter: diameter,
  16427. thickness: thickness,
  16428. tessellation: tessellation,
  16429. sideOrientation: sideOrientation,
  16430. updatable: updatable
  16431. };
  16432. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16433. };
  16434. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16435. var options = {
  16436. radius: radius,
  16437. tube: tube,
  16438. radialSegments: radialSegments,
  16439. tubularSegments: tubularSegments,
  16440. p: p,
  16441. q: q,
  16442. sideOrientation: sideOrientation,
  16443. updatable: updatable
  16444. };
  16445. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16446. };
  16447. // Lines
  16448. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16449. var options = {
  16450. points: points,
  16451. updatable: updatable,
  16452. instance: instance
  16453. };
  16454. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16455. };
  16456. // Dashed Lines
  16457. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16458. var options = {
  16459. points: points,
  16460. dashSize: dashSize,
  16461. gapSize: gapSize,
  16462. dashNb: dashNb,
  16463. updatable: updatable
  16464. };
  16465. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16466. };
  16467. // Extrusion
  16468. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16469. var options = {
  16470. shape: shape,
  16471. path: path,
  16472. scale: scale,
  16473. rotation: rotation,
  16474. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16475. sideOrientation: sideOrientation,
  16476. instance: instance,
  16477. updatable: updatable
  16478. };
  16479. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16480. };
  16481. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16482. var options = {
  16483. shape: shape,
  16484. path: path,
  16485. scaleFunction: scaleFunction,
  16486. rotationFunction: rotationFunction,
  16487. ribbonCloseArray: ribbonCloseArray,
  16488. ribbonClosePath: ribbonClosePath,
  16489. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16490. sideOrientation: sideOrientation,
  16491. instance: instance,
  16492. updatable: updatable
  16493. };
  16494. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16495. };
  16496. // Lathe
  16497. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16498. var options = {
  16499. shape: shape,
  16500. radius: radius,
  16501. tessellation: tessellation,
  16502. sideOrientation: sideOrientation,
  16503. updatable: updatable
  16504. };
  16505. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16506. };
  16507. // Plane & ground
  16508. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16509. var options = {
  16510. size: size,
  16511. width: size,
  16512. height: size,
  16513. sideOrientation: sideOrientation,
  16514. updatable: updatable
  16515. };
  16516. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16517. };
  16518. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16519. var options = {
  16520. width: width,
  16521. height: height,
  16522. subdivisions: subdivisions,
  16523. updatable: updatable
  16524. };
  16525. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16526. };
  16527. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16528. var options = {
  16529. xmin: xmin,
  16530. zmin: zmin,
  16531. xmax: xmax,
  16532. zmax: zmax,
  16533. subdivisions: subdivisions,
  16534. precision: precision,
  16535. updatable: updatable
  16536. };
  16537. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16538. };
  16539. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16540. var options = {
  16541. width: width,
  16542. height: height,
  16543. subdivisions: subdivisions,
  16544. minHeight: minHeight,
  16545. maxHeight: maxHeight,
  16546. updatable: updatable,
  16547. onReady: onReady
  16548. };
  16549. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16550. };
  16551. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16552. var options = {
  16553. path: path,
  16554. radius: radius,
  16555. tessellation: tessellation,
  16556. radiusFunction: radiusFunction,
  16557. arc: 1,
  16558. cap: cap,
  16559. updatable: updatable,
  16560. sideOrientation: sideOrientation,
  16561. instance: instance
  16562. };
  16563. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16564. };
  16565. Mesh.CreatePolyhedron = function (name, options, scene) {
  16566. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16567. };
  16568. Mesh.CreateIcoSphere = function (name, options, scene) {
  16569. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16570. };
  16571. // Decals
  16572. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16573. var options = {
  16574. position: position,
  16575. normal: normal,
  16576. size: size,
  16577. angle: angle
  16578. };
  16579. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16580. };
  16581. // Skeletons
  16582. /**
  16583. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16584. */
  16585. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16586. var source;
  16587. if (!this._sourcePositions) {
  16588. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16589. this._sourcePositions = new Float32Array(source);
  16590. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16591. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16592. }
  16593. }
  16594. return this._sourcePositions;
  16595. };
  16596. /**
  16597. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16598. */
  16599. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16600. var source;
  16601. if (!this._sourceNormals) {
  16602. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16603. this._sourceNormals = new Float32Array(source);
  16604. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16605. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16606. }
  16607. }
  16608. return this._sourceNormals;
  16609. };
  16610. /**
  16611. * Update the vertex buffers by applying transformation from the bones
  16612. * @param {skeleton} skeleton to apply
  16613. */
  16614. Mesh.prototype.applySkeleton = function (skeleton) {
  16615. if (!this.geometry) {
  16616. return;
  16617. }
  16618. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16619. return;
  16620. }
  16621. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16622. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16623. return this;
  16624. }
  16625. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16626. return this;
  16627. }
  16628. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16629. return this;
  16630. }
  16631. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16632. return this;
  16633. }
  16634. if (!this._sourcePositions) {
  16635. this.setPositionsForCPUSkinning();
  16636. }
  16637. if (!this._sourceNormals) {
  16638. this.setNormalsForCPUSkinning();
  16639. }
  16640. // positionsData checks for not being Float32Array will only pass at most once
  16641. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16642. if (!(positionsData instanceof Float32Array)) {
  16643. positionsData = new Float32Array(positionsData);
  16644. }
  16645. // normalsData checks for not being Float32Array will only pass at most once
  16646. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16647. if (!(normalsData instanceof Float32Array)) {
  16648. normalsData = new Float32Array(normalsData);
  16649. }
  16650. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16651. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16652. var needExtras = this.numBoneInfluencers > 4;
  16653. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16654. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16655. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16656. var tempVector3 = BABYLON.Vector3.Zero();
  16657. var finalMatrix = new BABYLON.Matrix();
  16658. var tempMatrix = new BABYLON.Matrix();
  16659. var matWeightIdx = 0;
  16660. var inf;
  16661. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16662. var weight;
  16663. for (inf = 0; inf < 4; inf++) {
  16664. weight = matricesWeightsData[matWeightIdx + inf];
  16665. if (weight > 0) {
  16666. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16667. finalMatrix.addToSelf(tempMatrix);
  16668. }
  16669. else
  16670. break;
  16671. }
  16672. if (needExtras) {
  16673. for (inf = 0; inf < 4; inf++) {
  16674. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16675. if (weight > 0) {
  16676. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16677. finalMatrix.addToSelf(tempMatrix);
  16678. }
  16679. else
  16680. break;
  16681. }
  16682. }
  16683. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16684. tempVector3.toArray(positionsData, index);
  16685. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16686. tempVector3.toArray(normalsData, index);
  16687. finalMatrix.reset();
  16688. }
  16689. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16690. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16691. return this;
  16692. };
  16693. // Tools
  16694. Mesh.MinMax = function (meshes) {
  16695. var minVector = null;
  16696. var maxVector = null;
  16697. for (var i in meshes) {
  16698. var mesh = meshes[i];
  16699. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16700. if (!minVector) {
  16701. minVector = boundingBox.minimumWorld;
  16702. maxVector = boundingBox.maximumWorld;
  16703. continue;
  16704. }
  16705. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16706. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16707. }
  16708. return {
  16709. min: minVector,
  16710. max: maxVector
  16711. };
  16712. };
  16713. Mesh.Center = function (meshesOrMinMaxVector) {
  16714. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16715. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16716. };
  16717. /**
  16718. * Merge the array of meshes into a single mesh for performance reasons.
  16719. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16720. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16721. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16722. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16723. */
  16724. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16725. if (disposeSource === void 0) { disposeSource = true; }
  16726. var index;
  16727. if (!allow32BitsIndices) {
  16728. var totalVertices = 0;
  16729. // Counting vertices
  16730. for (index = 0; index < meshes.length; index++) {
  16731. if (meshes[index]) {
  16732. totalVertices += meshes[index].getTotalVertices();
  16733. if (totalVertices > 65536) {
  16734. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16735. return null;
  16736. }
  16737. }
  16738. }
  16739. }
  16740. // Merge
  16741. var vertexData;
  16742. var otherVertexData;
  16743. var source;
  16744. for (index = 0; index < meshes.length; index++) {
  16745. if (meshes[index]) {
  16746. meshes[index].computeWorldMatrix(true);
  16747. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16748. otherVertexData.transform(meshes[index].getWorldMatrix());
  16749. if (vertexData) {
  16750. vertexData.merge(otherVertexData);
  16751. }
  16752. else {
  16753. vertexData = otherVertexData;
  16754. source = meshes[index];
  16755. }
  16756. }
  16757. }
  16758. if (!meshSubclass) {
  16759. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16760. }
  16761. vertexData.applyToMesh(meshSubclass);
  16762. // Setting properties
  16763. meshSubclass.material = source.material;
  16764. meshSubclass.checkCollisions = source.checkCollisions;
  16765. // Cleaning
  16766. if (disposeSource) {
  16767. for (index = 0; index < meshes.length; index++) {
  16768. if (meshes[index]) {
  16769. meshes[index].dispose();
  16770. }
  16771. }
  16772. }
  16773. return meshSubclass;
  16774. };
  16775. // Consts
  16776. Mesh._FRONTSIDE = 0;
  16777. Mesh._BACKSIDE = 1;
  16778. Mesh._DOUBLESIDE = 2;
  16779. Mesh._DEFAULTSIDE = 0;
  16780. Mesh._NO_CAP = 0;
  16781. Mesh._CAP_START = 1;
  16782. Mesh._CAP_END = 2;
  16783. Mesh._CAP_ALL = 3;
  16784. return Mesh;
  16785. })(BABYLON.AbstractMesh);
  16786. BABYLON.Mesh = Mesh;
  16787. })(BABYLON || (BABYLON = {}));
  16788. var BABYLON;
  16789. (function (BABYLON) {
  16790. var SubMesh = (function () {
  16791. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16792. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16793. this.materialIndex = materialIndex;
  16794. this.verticesStart = verticesStart;
  16795. this.verticesCount = verticesCount;
  16796. this.indexStart = indexStart;
  16797. this.indexCount = indexCount;
  16798. this._renderId = 0;
  16799. this._mesh = mesh;
  16800. this._renderingMesh = renderingMesh || mesh;
  16801. mesh.subMeshes.push(this);
  16802. this._trianglePlanes = [];
  16803. this._id = mesh.subMeshes.length - 1;
  16804. if (createBoundingBox) {
  16805. this.refreshBoundingInfo();
  16806. mesh.computeWorldMatrix(true);
  16807. }
  16808. }
  16809. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16810. get: function () {
  16811. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16812. },
  16813. enumerable: true,
  16814. configurable: true
  16815. });
  16816. SubMesh.prototype.getBoundingInfo = function () {
  16817. if (this.IsGlobal) {
  16818. return this._mesh.getBoundingInfo();
  16819. }
  16820. return this._boundingInfo;
  16821. };
  16822. SubMesh.prototype.getMesh = function () {
  16823. return this._mesh;
  16824. };
  16825. SubMesh.prototype.getRenderingMesh = function () {
  16826. return this._renderingMesh;
  16827. };
  16828. SubMesh.prototype.getMaterial = function () {
  16829. var rootMaterial = this._renderingMesh.material;
  16830. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16831. var multiMaterial = rootMaterial;
  16832. return multiMaterial.getSubMaterial(this.materialIndex);
  16833. }
  16834. if (!rootMaterial) {
  16835. return this._mesh.getScene().defaultMaterial;
  16836. }
  16837. return rootMaterial;
  16838. };
  16839. // Methods
  16840. SubMesh.prototype.refreshBoundingInfo = function () {
  16841. this._lastColliderWorldVertices = null;
  16842. if (this.IsGlobal) {
  16843. return;
  16844. }
  16845. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16846. if (!data) {
  16847. this._boundingInfo = this._mesh._boundingInfo;
  16848. return;
  16849. }
  16850. var indices = this._renderingMesh.getIndices();
  16851. var extend;
  16852. //is this the only submesh?
  16853. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16854. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16855. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16856. }
  16857. else {
  16858. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16859. }
  16860. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16861. };
  16862. SubMesh.prototype._checkCollision = function (collider) {
  16863. return this.getBoundingInfo()._checkCollision(collider);
  16864. };
  16865. SubMesh.prototype.updateBoundingInfo = function (world) {
  16866. if (!this.getBoundingInfo()) {
  16867. this.refreshBoundingInfo();
  16868. }
  16869. this.getBoundingInfo().update(world);
  16870. };
  16871. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16872. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16873. };
  16874. SubMesh.prototype.render = function (enableAlphaMode) {
  16875. this._renderingMesh.render(this, enableAlphaMode);
  16876. };
  16877. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16878. if (!this._linesIndexBuffer) {
  16879. var linesIndices = [];
  16880. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16881. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16882. }
  16883. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16884. this.linesIndexCount = linesIndices.length;
  16885. }
  16886. return this._linesIndexBuffer;
  16887. };
  16888. SubMesh.prototype.canIntersects = function (ray) {
  16889. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16890. };
  16891. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16892. var intersectInfo = null;
  16893. // Triangles test
  16894. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16895. var p0 = positions[indices[index]];
  16896. var p1 = positions[indices[index + 1]];
  16897. var p2 = positions[indices[index + 2]];
  16898. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16899. if (currentIntersectInfo) {
  16900. if (currentIntersectInfo.distance < 0) {
  16901. continue;
  16902. }
  16903. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16904. intersectInfo = currentIntersectInfo;
  16905. intersectInfo.faceId = index / 3;
  16906. if (fastCheck) {
  16907. break;
  16908. }
  16909. }
  16910. }
  16911. }
  16912. return intersectInfo;
  16913. };
  16914. // Clone
  16915. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16916. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16917. if (!this.IsGlobal) {
  16918. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16919. }
  16920. return result;
  16921. };
  16922. // Dispose
  16923. SubMesh.prototype.dispose = function () {
  16924. if (this._linesIndexBuffer) {
  16925. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16926. this._linesIndexBuffer = null;
  16927. }
  16928. // Remove from mesh
  16929. var index = this._mesh.subMeshes.indexOf(this);
  16930. this._mesh.subMeshes.splice(index, 1);
  16931. };
  16932. // Statics
  16933. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16934. var minVertexIndex = Number.MAX_VALUE;
  16935. var maxVertexIndex = -Number.MAX_VALUE;
  16936. renderingMesh = renderingMesh || mesh;
  16937. var indices = renderingMesh.getIndices();
  16938. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16939. var vertexIndex = indices[index];
  16940. if (vertexIndex < minVertexIndex)
  16941. minVertexIndex = vertexIndex;
  16942. if (vertexIndex > maxVertexIndex)
  16943. maxVertexIndex = vertexIndex;
  16944. }
  16945. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16946. };
  16947. return SubMesh;
  16948. })();
  16949. BABYLON.SubMesh = SubMesh;
  16950. })(BABYLON || (BABYLON = {}));
  16951. var BABYLON;
  16952. (function (BABYLON) {
  16953. var MeshBuilder = (function () {
  16954. function MeshBuilder() {
  16955. }
  16956. MeshBuilder.CreateBox = function (name, options, scene) {
  16957. var box = new BABYLON.Mesh(name, scene);
  16958. var vertexData = BABYLON.VertexData.CreateBox(options);
  16959. vertexData.applyToMesh(box, options.updatable);
  16960. return box;
  16961. };
  16962. MeshBuilder.CreateSphere = function (name, options, scene) {
  16963. var sphere = new BABYLON.Mesh(name, scene);
  16964. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16965. vertexData.applyToMesh(sphere, options.updatable);
  16966. return sphere;
  16967. };
  16968. MeshBuilder.CreateDisc = function (name, options, scene) {
  16969. var disc = new BABYLON.Mesh(name, scene);
  16970. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16971. vertexData.applyToMesh(disc, options.updatable);
  16972. return disc;
  16973. };
  16974. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16975. var sphere = new BABYLON.Mesh(name, scene);
  16976. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16977. vertexData.applyToMesh(sphere, options.updatable);
  16978. return sphere;
  16979. };
  16980. ;
  16981. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16982. var pathArray = options.pathArray;
  16983. var closeArray = options.closeArray;
  16984. var closePath = options.closePath;
  16985. var offset = options.offset;
  16986. var sideOrientation = options.sideOrientation;
  16987. var instance = options.instance;
  16988. var updatable = options.updatable;
  16989. if (instance) {
  16990. // positionFunction : ribbon case
  16991. // only pathArray and sideOrientation parameters are taken into account for positions update
  16992. var positionFunction = function (positions) {
  16993. var minlg = pathArray[0].length;
  16994. var i = 0;
  16995. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16996. for (var si = 1; si <= ns; si++) {
  16997. for (var p = 0; p < pathArray.length; p++) {
  16998. var path = pathArray[p];
  16999. var l = path.length;
  17000. minlg = (minlg < l) ? minlg : l;
  17001. var j = 0;
  17002. while (j < minlg) {
  17003. positions[i] = path[j].x;
  17004. positions[i + 1] = path[j].y;
  17005. positions[i + 2] = path[j].z;
  17006. j++;
  17007. i += 3;
  17008. }
  17009. if (instance._closePath) {
  17010. positions[i] = path[0].x;
  17011. positions[i + 1] = path[0].y;
  17012. positions[i + 2] = path[0].z;
  17013. i += 3;
  17014. }
  17015. }
  17016. }
  17017. };
  17018. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17019. positionFunction(positions);
  17020. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17021. if (!(instance.areNormalsFrozen)) {
  17022. var indices = instance.getIndices();
  17023. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17024. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17025. if (instance._closePath) {
  17026. var indexFirst = 0;
  17027. var indexLast = 0;
  17028. for (var p = 0; p < pathArray.length; p++) {
  17029. indexFirst = instance._idx[p] * 3;
  17030. if (p + 1 < pathArray.length) {
  17031. indexLast = (instance._idx[p + 1] - 1) * 3;
  17032. }
  17033. else {
  17034. indexLast = normals.length - 3;
  17035. }
  17036. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  17037. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  17038. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  17039. normals[indexLast] = normals[indexFirst];
  17040. normals[indexLast + 1] = normals[indexFirst + 1];
  17041. normals[indexLast + 2] = normals[indexFirst + 2];
  17042. }
  17043. }
  17044. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17045. }
  17046. return instance;
  17047. }
  17048. else {
  17049. var ribbon = new BABYLON.Mesh(name, scene);
  17050. ribbon.sideOrientation = sideOrientation;
  17051. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  17052. if (closePath) {
  17053. ribbon._idx = vertexData._idx;
  17054. }
  17055. ribbon._closePath = closePath;
  17056. ribbon._closeArray = closeArray;
  17057. vertexData.applyToMesh(ribbon, updatable);
  17058. return ribbon;
  17059. }
  17060. };
  17061. MeshBuilder.CreateCylinder = function (name, options, scene) {
  17062. var cylinder = new BABYLON.Mesh(name, scene);
  17063. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  17064. vertexData.applyToMesh(cylinder, options.updatable);
  17065. return cylinder;
  17066. };
  17067. MeshBuilder.CreateTorus = function (name, options, scene) {
  17068. var torus = new BABYLON.Mesh(name, scene);
  17069. var vertexData = BABYLON.VertexData.CreateTorus(options);
  17070. vertexData.applyToMesh(torus, options.updatable);
  17071. return torus;
  17072. };
  17073. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  17074. var torusKnot = new BABYLON.Mesh(name, scene);
  17075. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  17076. vertexData.applyToMesh(torusKnot, options.updatable);
  17077. return torusKnot;
  17078. };
  17079. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  17080. var instance = options.instance;
  17081. var lines = options.lines;
  17082. if (instance) {
  17083. var positionFunction = function (positions) {
  17084. var i = 0;
  17085. for (var l = 0; l < lines.length; l++) {
  17086. var points = lines[l];
  17087. for (var p = 0; p < points.length; p++) {
  17088. positions[i] = points[p].x;
  17089. positions[i + 1] = points[p].y;
  17090. positions[i + 2] = points[p].z;
  17091. i += 3;
  17092. }
  17093. }
  17094. };
  17095. instance.updateMeshPositions(positionFunction, false);
  17096. return instance;
  17097. }
  17098. // line system creation
  17099. var lineSystem = new BABYLON.LinesMesh(name, scene);
  17100. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  17101. vertexData.applyToMesh(lineSystem, options.updatable);
  17102. return lineSystem;
  17103. };
  17104. MeshBuilder.CreateLines = function (name, options, scene) {
  17105. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  17106. return lines;
  17107. };
  17108. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  17109. var points = options.points;
  17110. var instance = options.instance;
  17111. var gapSize = options.gapSize;
  17112. var dashNb = options.dashNb;
  17113. var dashSize = options.dashSize;
  17114. if (instance) {
  17115. var positionFunction = function (positions) {
  17116. var curvect = BABYLON.Vector3.Zero();
  17117. var nbSeg = positions.length / 6;
  17118. var lg = 0;
  17119. var nb = 0;
  17120. var shft = 0;
  17121. var dashshft = 0;
  17122. var curshft = 0;
  17123. var p = 0;
  17124. var i = 0;
  17125. var j = 0;
  17126. for (i = 0; i < points.length - 1; i++) {
  17127. points[i + 1].subtractToRef(points[i], curvect);
  17128. lg += curvect.length();
  17129. }
  17130. shft = lg / nbSeg;
  17131. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  17132. for (i = 0; i < points.length - 1; i++) {
  17133. points[i + 1].subtractToRef(points[i], curvect);
  17134. nb = Math.floor(curvect.length() / shft);
  17135. curvect.normalize();
  17136. j = 0;
  17137. while (j < nb && p < positions.length) {
  17138. curshft = shft * j;
  17139. positions[p] = points[i].x + curshft * curvect.x;
  17140. positions[p + 1] = points[i].y + curshft * curvect.y;
  17141. positions[p + 2] = points[i].z + curshft * curvect.z;
  17142. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  17143. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  17144. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  17145. p += 6;
  17146. j++;
  17147. }
  17148. }
  17149. while (p < positions.length) {
  17150. positions[p] = points[i].x;
  17151. positions[p + 1] = points[i].y;
  17152. positions[p + 2] = points[i].z;
  17153. p += 3;
  17154. }
  17155. };
  17156. instance.updateMeshPositions(positionFunction, false);
  17157. return instance;
  17158. }
  17159. // dashed lines creation
  17160. var dashedLines = new BABYLON.LinesMesh(name, scene);
  17161. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  17162. vertexData.applyToMesh(dashedLines, options.updatable);
  17163. dashedLines.dashSize = dashSize;
  17164. dashedLines.gapSize = gapSize;
  17165. return dashedLines;
  17166. };
  17167. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  17168. var path = options.path;
  17169. var shape = options.shape;
  17170. var scale = options.scale || 1;
  17171. var rotation = options.rotation || 0;
  17172. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17173. var updatable = options.updatable;
  17174. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17175. var instance = options.instance;
  17176. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  17177. };
  17178. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  17179. var path = options.path;
  17180. var shape = options.shape;
  17181. var scaleFunction = options.scaleFunction || (function () { return 1; });
  17182. var rotationFunction = options.rotationFunction || (function () { return 0; });
  17183. var ribbonCloseArray = options.ribbonCloseArray || false;
  17184. var ribbonClosePath = options.ribbonClosePath || false;
  17185. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17186. var updatable = options.updatable;
  17187. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17188. var instance = options.instance;
  17189. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  17190. };
  17191. MeshBuilder.CreateLathe = function (name, options, scene) {
  17192. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  17193. var closed = (options.closed === undefined) ? true : options.closed;
  17194. var shape = options.shape;
  17195. var radius = options.radius || 1;
  17196. var tessellation = options.tessellation || 64;
  17197. var updatable = options.updatable;
  17198. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17199. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17200. var pi2 = Math.PI * 2;
  17201. var paths = new Array();
  17202. var i = 0;
  17203. var p = 0;
  17204. var step = pi2 / tessellation * arc;
  17205. var rotated;
  17206. var path = new Array();
  17207. ;
  17208. for (i = 0; i <= tessellation; i++) {
  17209. var path = [];
  17210. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  17211. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  17212. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  17213. }
  17214. for (p = 0; p < shape.length; p++) {
  17215. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  17216. path.push(rotated);
  17217. }
  17218. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  17219. 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));
  17220. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  17221. }
  17222. paths.push(path);
  17223. }
  17224. // lathe ribbon
  17225. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  17226. return lathe;
  17227. };
  17228. MeshBuilder.CreatePlane = function (name, options, scene) {
  17229. var plane = new BABYLON.Mesh(name, scene);
  17230. var vertexData = BABYLON.VertexData.CreatePlane(options);
  17231. vertexData.applyToMesh(plane, options.updatable);
  17232. if (options.sourcePlane) {
  17233. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  17234. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  17235. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  17236. plane.rotate(vectorProduct, product);
  17237. }
  17238. return plane;
  17239. };
  17240. MeshBuilder.CreateGround = function (name, options, scene) {
  17241. var ground = new BABYLON.GroundMesh(name, scene);
  17242. ground._setReady(false);
  17243. ground._subdivisions = options.subdivisions || 1;
  17244. ground._width = options.width || 1;
  17245. ground._height = options.height || 1;
  17246. ground._maxX = ground._width / 2;
  17247. ground._maxZ = ground._height / 2;
  17248. ground._minX = -ground._maxX;
  17249. ground._minZ = -ground._maxZ;
  17250. var vertexData = BABYLON.VertexData.CreateGround(options);
  17251. vertexData.applyToMesh(ground, options.updatable);
  17252. ground._setReady(true);
  17253. return ground;
  17254. };
  17255. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  17256. var tiledGround = new BABYLON.Mesh(name, scene);
  17257. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  17258. vertexData.applyToMesh(tiledGround, options.updatable);
  17259. return tiledGround;
  17260. };
  17261. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  17262. var width = options.width || 10;
  17263. var height = options.height || 10;
  17264. var subdivisions = options.subdivisions || 1;
  17265. var minHeight = options.minHeight;
  17266. var maxHeight = options.maxHeight || 10;
  17267. var updatable = options.updatable;
  17268. var onReady = options.onReady;
  17269. var ground = new BABYLON.GroundMesh(name, scene);
  17270. ground._subdivisions = subdivisions;
  17271. ground._width = width;
  17272. ground._height = height;
  17273. ground._maxX = ground._width / 2;
  17274. ground._maxZ = ground._height / 2;
  17275. ground._minX = -ground._maxX;
  17276. ground._minZ = -ground._maxZ;
  17277. ground._setReady(false);
  17278. var onload = function (img) {
  17279. // Getting height map data
  17280. var canvas = document.createElement("canvas");
  17281. var context = canvas.getContext("2d");
  17282. var bufferWidth = img.width;
  17283. var bufferHeight = img.height;
  17284. canvas.width = bufferWidth;
  17285. canvas.height = bufferHeight;
  17286. context.drawImage(img, 0, 0);
  17287. // Create VertexData from map data
  17288. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17289. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  17290. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  17291. width: width, height: height,
  17292. subdivisions: subdivisions,
  17293. minHeight: minHeight, maxHeight: maxHeight,
  17294. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  17295. });
  17296. vertexData.applyToMesh(ground, updatable);
  17297. ground._setReady(true);
  17298. //execute ready callback, if set
  17299. if (onReady) {
  17300. onReady(ground);
  17301. }
  17302. };
  17303. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17304. return ground;
  17305. };
  17306. MeshBuilder.CreateTube = function (name, options, scene) {
  17307. var path = options.path;
  17308. var radius = options.radius || 1;
  17309. var tessellation = options.tessellation || 64;
  17310. var radiusFunction = options.radiusFunction;
  17311. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17312. var updatable = options.updatable;
  17313. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17314. var instance = options.instance;
  17315. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  17316. // tube geometry
  17317. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  17318. var tangents = path3D.getTangents();
  17319. var normals = path3D.getNormals();
  17320. var distances = path3D.getDistances();
  17321. var pi2 = Math.PI * 2;
  17322. var step = pi2 / tessellation * arc;
  17323. var returnRadius = function () { return radius; };
  17324. var radiusFunctionFinal = radiusFunction || returnRadius;
  17325. var circlePath;
  17326. var rad;
  17327. var normal;
  17328. var rotated;
  17329. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17330. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17331. for (var i = 0; i < path.length; i++) {
  17332. rad = radiusFunctionFinal(i, distances[i]); // current radius
  17333. circlePath = Array(); // current circle array
  17334. normal = normals[i]; // current normal
  17335. for (var t = 0; t < tessellation; t++) {
  17336. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  17337. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  17338. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  17339. rotated.scaleInPlace(rad).addInPlace(path[i]);
  17340. circlePath[t] = rotated;
  17341. }
  17342. circlePaths[index] = circlePath;
  17343. index++;
  17344. }
  17345. // cap
  17346. var capPath = function (nbPoints, pathIndex) {
  17347. var pointCap = Array();
  17348. for (var i = 0; i < nbPoints; i++) {
  17349. pointCap.push(path[pathIndex]);
  17350. }
  17351. return pointCap;
  17352. };
  17353. switch (cap) {
  17354. case BABYLON.Mesh.NO_CAP:
  17355. break;
  17356. case BABYLON.Mesh.CAP_START:
  17357. circlePaths[0] = capPath(tessellation, 0);
  17358. circlePaths[1] = circlePaths[2].slice(0);
  17359. break;
  17360. case BABYLON.Mesh.CAP_END:
  17361. circlePaths[index] = circlePaths[index - 1].slice(0);
  17362. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17363. break;
  17364. case BABYLON.Mesh.CAP_ALL:
  17365. circlePaths[0] = capPath(tessellation, 0);
  17366. circlePaths[1] = circlePaths[2].slice(0);
  17367. circlePaths[index] = circlePaths[index - 1].slice(0);
  17368. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17369. break;
  17370. default:
  17371. break;
  17372. }
  17373. return circlePaths;
  17374. };
  17375. var path3D;
  17376. var pathArray;
  17377. if (instance) {
  17378. var arc = options.arc || instance.arc;
  17379. path3D = (instance.path3D).update(path);
  17380. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17381. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17382. instance.path3D = path3D;
  17383. instance.pathArray = pathArray;
  17384. instance.arc = arc;
  17385. return instance;
  17386. }
  17387. // tube creation
  17388. path3D = new BABYLON.Path3D(path);
  17389. var newPathArray = new Array();
  17390. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17391. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17392. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17393. tube.pathArray = pathArray;
  17394. tube.path3D = path3D;
  17395. tube.tessellation = tessellation;
  17396. tube.cap = cap;
  17397. tube.arc = options.arc;
  17398. return tube;
  17399. };
  17400. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17401. var polyhedron = new BABYLON.Mesh(name, scene);
  17402. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17403. vertexData.applyToMesh(polyhedron, options.updatable);
  17404. return polyhedron;
  17405. };
  17406. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17407. var indices = sourceMesh.getIndices();
  17408. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17409. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17410. var position = options.position || BABYLON.Vector3.Zero();
  17411. var normal = options.normal || BABYLON.Vector3.Up();
  17412. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17413. var angle = options.angle || 0;
  17414. // Getting correct rotation
  17415. if (!normal) {
  17416. var target = new BABYLON.Vector3(0, 0, 1);
  17417. var camera = sourceMesh.getScene().activeCamera;
  17418. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17419. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17420. }
  17421. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17422. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17423. var pitch = Math.atan2(normal.y, len);
  17424. // Matrix
  17425. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17426. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17427. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17428. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17429. var vertexData = new BABYLON.VertexData();
  17430. vertexData.indices = [];
  17431. vertexData.positions = [];
  17432. vertexData.normals = [];
  17433. vertexData.uvs = [];
  17434. var currentVertexDataIndex = 0;
  17435. var extractDecalVector3 = function (indexId) {
  17436. var vertexId = indices[indexId];
  17437. var result = new BABYLON.PositionNormalVertex();
  17438. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17439. // Send vector to decal local world
  17440. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17441. // Get normal
  17442. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17443. return result;
  17444. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17445. var clip = function (vertices, axis) {
  17446. if (vertices.length === 0) {
  17447. return vertices;
  17448. }
  17449. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17450. var clipVertices = function (v0, v1) {
  17451. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17452. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17453. };
  17454. var result = new Array();
  17455. for (var index = 0; index < vertices.length; index += 3) {
  17456. var v1Out;
  17457. var v2Out;
  17458. var v3Out;
  17459. var total = 0;
  17460. var nV1, nV2, nV3, nV4;
  17461. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17462. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17463. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17464. v1Out = d1 > 0;
  17465. v2Out = d2 > 0;
  17466. v3Out = d3 > 0;
  17467. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17468. switch (total) {
  17469. case 0:
  17470. result.push(vertices[index]);
  17471. result.push(vertices[index + 1]);
  17472. result.push(vertices[index + 2]);
  17473. break;
  17474. case 1:
  17475. if (v1Out) {
  17476. nV1 = vertices[index + 1];
  17477. nV2 = vertices[index + 2];
  17478. nV3 = clipVertices(vertices[index], nV1);
  17479. nV4 = clipVertices(vertices[index], nV2);
  17480. }
  17481. if (v2Out) {
  17482. nV1 = vertices[index];
  17483. nV2 = vertices[index + 2];
  17484. nV3 = clipVertices(vertices[index + 1], nV1);
  17485. nV4 = clipVertices(vertices[index + 1], nV2);
  17486. result.push(nV3);
  17487. result.push(nV2.clone());
  17488. result.push(nV1.clone());
  17489. result.push(nV2.clone());
  17490. result.push(nV3.clone());
  17491. result.push(nV4);
  17492. break;
  17493. }
  17494. if (v3Out) {
  17495. nV1 = vertices[index];
  17496. nV2 = vertices[index + 1];
  17497. nV3 = clipVertices(vertices[index + 2], nV1);
  17498. nV4 = clipVertices(vertices[index + 2], nV2);
  17499. }
  17500. result.push(nV1.clone());
  17501. result.push(nV2.clone());
  17502. result.push(nV3);
  17503. result.push(nV4);
  17504. result.push(nV3.clone());
  17505. result.push(nV2.clone());
  17506. break;
  17507. case 2:
  17508. if (!v1Out) {
  17509. nV1 = vertices[index].clone();
  17510. nV2 = clipVertices(nV1, vertices[index + 1]);
  17511. nV3 = clipVertices(nV1, vertices[index + 2]);
  17512. result.push(nV1);
  17513. result.push(nV2);
  17514. result.push(nV3);
  17515. }
  17516. if (!v2Out) {
  17517. nV1 = vertices[index + 1].clone();
  17518. nV2 = clipVertices(nV1, vertices[index + 2]);
  17519. nV3 = clipVertices(nV1, vertices[index]);
  17520. result.push(nV1);
  17521. result.push(nV2);
  17522. result.push(nV3);
  17523. }
  17524. if (!v3Out) {
  17525. nV1 = vertices[index + 2].clone();
  17526. nV2 = clipVertices(nV1, vertices[index]);
  17527. nV3 = clipVertices(nV1, vertices[index + 1]);
  17528. result.push(nV1);
  17529. result.push(nV2);
  17530. result.push(nV3);
  17531. }
  17532. break;
  17533. case 3:
  17534. break;
  17535. }
  17536. }
  17537. return result;
  17538. };
  17539. for (var index = 0; index < indices.length; index += 3) {
  17540. var faceVertices = new Array();
  17541. faceVertices.push(extractDecalVector3(index));
  17542. faceVertices.push(extractDecalVector3(index + 1));
  17543. faceVertices.push(extractDecalVector3(index + 2));
  17544. // Clip
  17545. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17546. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17547. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17548. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17549. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17550. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17551. if (faceVertices.length === 0) {
  17552. continue;
  17553. }
  17554. // Add UVs and get back to world
  17555. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17556. var vertex = faceVertices[vIndex];
  17557. //TODO check for Int32Array
  17558. vertexData.indices.push(currentVertexDataIndex);
  17559. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17560. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17561. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17562. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17563. currentVertexDataIndex++;
  17564. }
  17565. }
  17566. // Return mesh
  17567. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17568. vertexData.applyToMesh(decal);
  17569. decal.position = position.clone();
  17570. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17571. return decal;
  17572. };
  17573. // Privates
  17574. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17575. // extrusion geometry
  17576. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17577. var tangents = path3D.getTangents();
  17578. var normals = path3D.getNormals();
  17579. var binormals = path3D.getBinormals();
  17580. var distances = path3D.getDistances();
  17581. var angle = 0;
  17582. var returnScale = function () { return scale; };
  17583. var returnRotation = function () { return rotation; };
  17584. var rotate = custom ? rotateFunction : returnRotation;
  17585. var scl = custom ? scaleFunction : returnScale;
  17586. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17587. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17588. for (var i = 0; i < curve.length; i++) {
  17589. var shapePath = new Array();
  17590. var angleStep = rotate(i, distances[i]);
  17591. var scaleRatio = scl(i, distances[i]);
  17592. for (var p = 0; p < shape.length; p++) {
  17593. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17594. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17595. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17596. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17597. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17598. shapePath[p] = rotated;
  17599. }
  17600. shapePaths[index] = shapePath;
  17601. angle += angleStep;
  17602. index++;
  17603. }
  17604. // cap
  17605. var capPath = function (shapePath) {
  17606. var pointCap = Array();
  17607. var barycenter = BABYLON.Vector3.Zero();
  17608. var i;
  17609. for (i = 0; i < shapePath.length; i++) {
  17610. barycenter.addInPlace(shapePath[i]);
  17611. }
  17612. barycenter.scaleInPlace(1 / shapePath.length);
  17613. for (i = 0; i < shapePath.length; i++) {
  17614. pointCap.push(barycenter);
  17615. }
  17616. return pointCap;
  17617. };
  17618. switch (cap) {
  17619. case BABYLON.Mesh.NO_CAP:
  17620. break;
  17621. case BABYLON.Mesh.CAP_START:
  17622. shapePaths[0] = capPath(shapePaths[2]);
  17623. shapePaths[1] = shapePaths[2].slice(0);
  17624. break;
  17625. case BABYLON.Mesh.CAP_END:
  17626. shapePaths[index] = shapePaths[index - 1];
  17627. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17628. break;
  17629. case BABYLON.Mesh.CAP_ALL:
  17630. shapePaths[0] = capPath(shapePaths[2]);
  17631. shapePaths[1] = shapePaths[2].slice(0);
  17632. shapePaths[index] = shapePaths[index - 1];
  17633. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17634. break;
  17635. default:
  17636. break;
  17637. }
  17638. return shapePaths;
  17639. };
  17640. var path3D;
  17641. var pathArray;
  17642. if (instance) {
  17643. path3D = (instance.path3D).update(curve);
  17644. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17645. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17646. return instance;
  17647. }
  17648. // extruded shape creation
  17649. path3D = new BABYLON.Path3D(curve);
  17650. var newShapePaths = new Array();
  17651. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17652. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17653. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17654. extrudedGeneric.pathArray = pathArray;
  17655. extrudedGeneric.path3D = path3D;
  17656. extrudedGeneric.cap = cap;
  17657. return extrudedGeneric;
  17658. };
  17659. return MeshBuilder;
  17660. })();
  17661. BABYLON.MeshBuilder = MeshBuilder;
  17662. })(BABYLON || (BABYLON = {}));
  17663. var BABYLON;
  17664. (function (BABYLON) {
  17665. var BaseTexture = (function () {
  17666. function BaseTexture(scene) {
  17667. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17668. this.hasAlpha = false;
  17669. this.getAlphaFromRGB = false;
  17670. this.level = 1;
  17671. this.isCube = false;
  17672. this.isRenderTarget = false;
  17673. this.animations = new Array();
  17674. this.coordinatesIndex = 0;
  17675. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17676. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17677. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17678. this.anisotropicFilteringLevel = 4;
  17679. this._scene = scene;
  17680. this._scene.textures.push(this);
  17681. }
  17682. BaseTexture.prototype.getScene = function () {
  17683. return this._scene;
  17684. };
  17685. BaseTexture.prototype.getTextureMatrix = function () {
  17686. return null;
  17687. };
  17688. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17689. return null;
  17690. };
  17691. BaseTexture.prototype.getInternalTexture = function () {
  17692. return this._texture;
  17693. };
  17694. BaseTexture.prototype.isReady = function () {
  17695. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17696. return true;
  17697. }
  17698. if (this._texture) {
  17699. return this._texture.isReady;
  17700. }
  17701. return false;
  17702. };
  17703. BaseTexture.prototype.getSize = function () {
  17704. if (this._texture._width) {
  17705. return { width: this._texture._width, height: this._texture._height };
  17706. }
  17707. if (this._texture._size) {
  17708. return { width: this._texture._size, height: this._texture._size };
  17709. }
  17710. return { width: 0, height: 0 };
  17711. };
  17712. BaseTexture.prototype.getBaseSize = function () {
  17713. if (!this.isReady())
  17714. return { width: 0, height: 0 };
  17715. if (this._texture._size) {
  17716. return { width: this._texture._size, height: this._texture._size };
  17717. }
  17718. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17719. };
  17720. BaseTexture.prototype.scale = function (ratio) {
  17721. };
  17722. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17723. get: function () {
  17724. return false;
  17725. },
  17726. enumerable: true,
  17727. configurable: true
  17728. });
  17729. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17730. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17731. for (var index = 0; index < texturesCache.length; index++) {
  17732. var texturesCacheEntry = texturesCache[index];
  17733. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17734. texturesCache.splice(index, 1);
  17735. return;
  17736. }
  17737. }
  17738. };
  17739. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17740. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17741. for (var index = 0; index < texturesCache.length; index++) {
  17742. var texturesCacheEntry = texturesCache[index];
  17743. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17744. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17745. texturesCacheEntry.references++;
  17746. return texturesCacheEntry;
  17747. }
  17748. }
  17749. }
  17750. return null;
  17751. };
  17752. BaseTexture.prototype.delayLoad = function () {
  17753. };
  17754. BaseTexture.prototype.clone = function () {
  17755. return null;
  17756. };
  17757. BaseTexture.prototype.releaseInternalTexture = function () {
  17758. if (this._texture) {
  17759. this._scene.getEngine().releaseInternalTexture(this._texture);
  17760. delete this._texture;
  17761. }
  17762. };
  17763. BaseTexture.prototype.dispose = function () {
  17764. // Animations
  17765. this.getScene().stopAnimation(this);
  17766. // Remove from scene
  17767. var index = this._scene.textures.indexOf(this);
  17768. if (index >= 0) {
  17769. this._scene.textures.splice(index, 1);
  17770. }
  17771. if (this._texture === undefined) {
  17772. return;
  17773. }
  17774. // Release
  17775. this.releaseInternalTexture();
  17776. // Callback
  17777. if (this.onDispose) {
  17778. this.onDispose();
  17779. }
  17780. };
  17781. BaseTexture.prototype.serialize = function () {
  17782. var serializationObject = {};
  17783. if (!this.name) {
  17784. return null;
  17785. }
  17786. serializationObject.name = this.name;
  17787. serializationObject.hasAlpha = this.hasAlpha;
  17788. serializationObject.level = this.level;
  17789. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17790. serializationObject.coordinatesMode = this.coordinatesMode;
  17791. serializationObject.wrapU = this.wrapU;
  17792. serializationObject.wrapV = this.wrapV;
  17793. // Animations
  17794. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17795. return serializationObject;
  17796. };
  17797. return BaseTexture;
  17798. })();
  17799. BABYLON.BaseTexture = BaseTexture;
  17800. })(BABYLON || (BABYLON = {}));
  17801. var BABYLON;
  17802. (function (BABYLON) {
  17803. var Texture = (function (_super) {
  17804. __extends(Texture, _super);
  17805. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17806. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17807. if (onLoad === void 0) { onLoad = null; }
  17808. if (onError === void 0) { onError = null; }
  17809. if (buffer === void 0) { buffer = null; }
  17810. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17811. _super.call(this, scene);
  17812. this.uOffset = 0;
  17813. this.vOffset = 0;
  17814. this.uScale = 1.0;
  17815. this.vScale = 1.0;
  17816. this.uAng = 0;
  17817. this.vAng = 0;
  17818. this.wAng = 0;
  17819. this.name = url;
  17820. this.url = url;
  17821. this._noMipmap = noMipmap;
  17822. this._invertY = invertY;
  17823. this._samplingMode = samplingMode;
  17824. this._buffer = buffer;
  17825. this._deleteBuffer = deleteBuffer;
  17826. if (!url) {
  17827. return;
  17828. }
  17829. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17830. if (!this._texture) {
  17831. if (!scene.useDelayedTextureLoading) {
  17832. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17833. if (deleteBuffer) {
  17834. delete this._buffer;
  17835. }
  17836. }
  17837. else {
  17838. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17839. this._delayedOnLoad = onLoad;
  17840. this._delayedOnError = onError;
  17841. }
  17842. }
  17843. else {
  17844. BABYLON.Tools.SetImmediate(function () {
  17845. if (onLoad) {
  17846. onLoad();
  17847. }
  17848. });
  17849. }
  17850. }
  17851. Texture.prototype.delayLoad = function () {
  17852. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17853. return;
  17854. }
  17855. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17856. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17857. if (!this._texture) {
  17858. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  17859. if (this._deleteBuffer) {
  17860. delete this._buffer;
  17861. }
  17862. }
  17863. };
  17864. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17865. if (!this._texture) {
  17866. return;
  17867. }
  17868. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17869. };
  17870. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17871. x *= this.uScale;
  17872. y *= this.vScale;
  17873. x -= 0.5 * this.uScale;
  17874. y -= 0.5 * this.vScale;
  17875. z -= 0.5;
  17876. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17877. t.x += 0.5 * this.uScale + this.uOffset;
  17878. t.y += 0.5 * this.vScale + this.vOffset;
  17879. t.z += 0.5;
  17880. };
  17881. Texture.prototype.getTextureMatrix = function () {
  17882. if (this.uOffset === this._cachedUOffset &&
  17883. this.vOffset === this._cachedVOffset &&
  17884. this.uScale === this._cachedUScale &&
  17885. this.vScale === this._cachedVScale &&
  17886. this.uAng === this._cachedUAng &&
  17887. this.vAng === this._cachedVAng &&
  17888. this.wAng === this._cachedWAng) {
  17889. return this._cachedTextureMatrix;
  17890. }
  17891. this._cachedUOffset = this.uOffset;
  17892. this._cachedVOffset = this.vOffset;
  17893. this._cachedUScale = this.uScale;
  17894. this._cachedVScale = this.vScale;
  17895. this._cachedUAng = this.uAng;
  17896. this._cachedVAng = this.vAng;
  17897. this._cachedWAng = this.wAng;
  17898. if (!this._cachedTextureMatrix) {
  17899. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17900. this._rowGenerationMatrix = new BABYLON.Matrix();
  17901. this._t0 = BABYLON.Vector3.Zero();
  17902. this._t1 = BABYLON.Vector3.Zero();
  17903. this._t2 = BABYLON.Vector3.Zero();
  17904. }
  17905. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17906. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17907. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17908. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17909. this._t1.subtractInPlace(this._t0);
  17910. this._t2.subtractInPlace(this._t0);
  17911. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17912. this._cachedTextureMatrix.m[0] = this._t1.x;
  17913. this._cachedTextureMatrix.m[1] = this._t1.y;
  17914. this._cachedTextureMatrix.m[2] = this._t1.z;
  17915. this._cachedTextureMatrix.m[4] = this._t2.x;
  17916. this._cachedTextureMatrix.m[5] = this._t2.y;
  17917. this._cachedTextureMatrix.m[6] = this._t2.z;
  17918. this._cachedTextureMatrix.m[8] = this._t0.x;
  17919. this._cachedTextureMatrix.m[9] = this._t0.y;
  17920. this._cachedTextureMatrix.m[10] = this._t0.z;
  17921. return this._cachedTextureMatrix;
  17922. };
  17923. Texture.prototype.getReflectionTextureMatrix = function () {
  17924. if (this.uOffset === this._cachedUOffset &&
  17925. this.vOffset === this._cachedVOffset &&
  17926. this.uScale === this._cachedUScale &&
  17927. this.vScale === this._cachedVScale &&
  17928. this.coordinatesMode === this._cachedCoordinatesMode) {
  17929. return this._cachedTextureMatrix;
  17930. }
  17931. if (!this._cachedTextureMatrix) {
  17932. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17933. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17934. }
  17935. this._cachedCoordinatesMode = this.coordinatesMode;
  17936. switch (this.coordinatesMode) {
  17937. case Texture.PLANAR_MODE:
  17938. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17939. this._cachedTextureMatrix[0] = this.uScale;
  17940. this._cachedTextureMatrix[5] = this.vScale;
  17941. this._cachedTextureMatrix[12] = this.uOffset;
  17942. this._cachedTextureMatrix[13] = this.vOffset;
  17943. break;
  17944. case Texture.PROJECTION_MODE:
  17945. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17946. this._projectionModeMatrix.m[0] = 0.5;
  17947. this._projectionModeMatrix.m[5] = -0.5;
  17948. this._projectionModeMatrix.m[10] = 0.0;
  17949. this._projectionModeMatrix.m[12] = 0.5;
  17950. this._projectionModeMatrix.m[13] = 0.5;
  17951. this._projectionModeMatrix.m[14] = 1.0;
  17952. this._projectionModeMatrix.m[15] = 1.0;
  17953. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17954. break;
  17955. default:
  17956. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17957. break;
  17958. }
  17959. return this._cachedTextureMatrix;
  17960. };
  17961. Texture.prototype.clone = function () {
  17962. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17963. // Base texture
  17964. newTexture.hasAlpha = this.hasAlpha;
  17965. newTexture.level = this.level;
  17966. newTexture.wrapU = this.wrapU;
  17967. newTexture.wrapV = this.wrapV;
  17968. newTexture.coordinatesIndex = this.coordinatesIndex;
  17969. newTexture.coordinatesMode = this.coordinatesMode;
  17970. // Texture
  17971. newTexture.uOffset = this.uOffset;
  17972. newTexture.vOffset = this.vOffset;
  17973. newTexture.uScale = this.uScale;
  17974. newTexture.vScale = this.vScale;
  17975. newTexture.uAng = this.uAng;
  17976. newTexture.vAng = this.vAng;
  17977. newTexture.wAng = this.wAng;
  17978. return newTexture;
  17979. };
  17980. Texture.prototype.serialize = function () {
  17981. if (!this.name) {
  17982. return null;
  17983. }
  17984. var serializationObject = _super.prototype.serialize.call(this);
  17985. serializationObject.uOffset = this.uOffset;
  17986. serializationObject.vOffset = this.vOffset;
  17987. serializationObject.uScale = this.uScale;
  17988. serializationObject.vScale = this.vScale;
  17989. serializationObject.uAng = this.uAng;
  17990. serializationObject.vAng = this.vAng;
  17991. serializationObject.wAng = this.wAng;
  17992. return serializationObject;
  17993. };
  17994. // Statics
  17995. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17996. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17997. if (onLoad === void 0) { onLoad = null; }
  17998. if (onError === void 0) { onError = null; }
  17999. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  18000. };
  18001. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  18002. if (parsedTexture.isCube) {
  18003. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  18004. }
  18005. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18006. return null;
  18007. }
  18008. var texture;
  18009. if (parsedTexture.mirrorPlane) {
  18010. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18011. texture._waitingRenderList = parsedTexture.renderList;
  18012. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18013. }
  18014. else if (parsedTexture.isRenderTarget) {
  18015. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18016. texture._waitingRenderList = parsedTexture.renderList;
  18017. }
  18018. else {
  18019. if (parsedTexture.base64String) {
  18020. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  18021. }
  18022. else {
  18023. texture = new Texture(rootUrl + parsedTexture.name, scene);
  18024. }
  18025. }
  18026. texture.name = parsedTexture.name;
  18027. texture.hasAlpha = parsedTexture.hasAlpha;
  18028. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18029. texture.level = parsedTexture.level;
  18030. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18031. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18032. texture.uOffset = parsedTexture.uOffset;
  18033. texture.vOffset = parsedTexture.vOffset;
  18034. texture.uScale = parsedTexture.uScale;
  18035. texture.vScale = parsedTexture.vScale;
  18036. texture.uAng = parsedTexture.uAng;
  18037. texture.vAng = parsedTexture.vAng;
  18038. texture.wAng = parsedTexture.wAng;
  18039. texture.wrapU = parsedTexture.wrapU;
  18040. texture.wrapV = parsedTexture.wrapV;
  18041. // Animations
  18042. if (parsedTexture.animations) {
  18043. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18044. var parsedAnimation = parsedTexture.animations[animationIndex];
  18045. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18046. }
  18047. }
  18048. return texture;
  18049. };
  18050. // Constants
  18051. Texture.NEAREST_SAMPLINGMODE = 1;
  18052. Texture.BILINEAR_SAMPLINGMODE = 2;
  18053. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18054. Texture.EXPLICIT_MODE = 0;
  18055. Texture.SPHERICAL_MODE = 1;
  18056. Texture.PLANAR_MODE = 2;
  18057. Texture.CUBIC_MODE = 3;
  18058. Texture.PROJECTION_MODE = 4;
  18059. Texture.SKYBOX_MODE = 5;
  18060. Texture.INVCUBIC_MODE = 6;
  18061. Texture.EQUIRECTANGULAR_MODE = 7;
  18062. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18063. Texture.CLAMP_ADDRESSMODE = 0;
  18064. Texture.WRAP_ADDRESSMODE = 1;
  18065. Texture.MIRROR_ADDRESSMODE = 2;
  18066. return Texture;
  18067. })(BABYLON.BaseTexture);
  18068. BABYLON.Texture = Texture;
  18069. })(BABYLON || (BABYLON = {}));
  18070. var BABYLON;
  18071. (function (BABYLON) {
  18072. var CubeTexture = (function (_super) {
  18073. __extends(CubeTexture, _super);
  18074. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  18075. _super.call(this, scene);
  18076. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  18077. this.name = rootUrl;
  18078. this.url = rootUrl;
  18079. this._noMipmap = noMipmap;
  18080. this.hasAlpha = false;
  18081. if (!rootUrl && !files) {
  18082. return;
  18083. }
  18084. this._texture = this._getFromCache(rootUrl, noMipmap);
  18085. if (!files) {
  18086. if (!extensions) {
  18087. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  18088. }
  18089. files = [];
  18090. for (var index = 0; index < extensions.length; index++) {
  18091. files.push(rootUrl + extensions[index]);
  18092. }
  18093. this._extensions = extensions;
  18094. }
  18095. this._files = files;
  18096. if (!this._texture) {
  18097. if (!scene.useDelayedTextureLoading) {
  18098. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  18099. }
  18100. else {
  18101. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18102. }
  18103. }
  18104. this.isCube = true;
  18105. this._textureMatrix = BABYLON.Matrix.Identity();
  18106. }
  18107. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  18108. return new CubeTexture("", scene, null, noMipmap, files);
  18109. };
  18110. CubeTexture.prototype.clone = function () {
  18111. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  18112. // Base texture
  18113. newTexture.level = this.level;
  18114. newTexture.wrapU = this.wrapU;
  18115. newTexture.wrapV = this.wrapV;
  18116. newTexture.coordinatesIndex = this.coordinatesIndex;
  18117. newTexture.coordinatesMode = this.coordinatesMode;
  18118. return newTexture;
  18119. };
  18120. // Methods
  18121. CubeTexture.prototype.delayLoad = function () {
  18122. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18123. return;
  18124. }
  18125. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18126. this._texture = this._getFromCache(this.url, this._noMipmap);
  18127. if (!this._texture) {
  18128. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  18129. }
  18130. };
  18131. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  18132. return this._textureMatrix;
  18133. };
  18134. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  18135. var texture = null;
  18136. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  18137. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  18138. texture.name = parsedTexture.name;
  18139. texture.hasAlpha = parsedTexture.hasAlpha;
  18140. texture.level = parsedTexture.level;
  18141. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18142. }
  18143. return texture;
  18144. };
  18145. CubeTexture.prototype.serialize = function () {
  18146. if (!this.name) {
  18147. return null;
  18148. }
  18149. var serializationObject = {};
  18150. serializationObject.name = this.name;
  18151. serializationObject.hasAlpha = this.hasAlpha;
  18152. serializationObject.isCube = true;
  18153. serializationObject.level = this.level;
  18154. serializationObject.coordinatesMode = this.coordinatesMode;
  18155. return serializationObject;
  18156. };
  18157. return CubeTexture;
  18158. })(BABYLON.BaseTexture);
  18159. BABYLON.CubeTexture = CubeTexture;
  18160. })(BABYLON || (BABYLON = {}));
  18161. var BABYLON;
  18162. (function (BABYLON) {
  18163. var RenderTargetTexture = (function (_super) {
  18164. __extends(RenderTargetTexture, _super);
  18165. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  18166. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  18167. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  18168. if (isCube === void 0) { isCube = false; }
  18169. _super.call(this, null, scene, !generateMipMaps);
  18170. this.isCube = isCube;
  18171. this.renderList = new Array();
  18172. this.renderParticles = true;
  18173. this.renderSprites = false;
  18174. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  18175. this._currentRefreshId = -1;
  18176. this._refreshRate = 1;
  18177. this.name = name;
  18178. this.isRenderTarget = true;
  18179. this._size = size;
  18180. this._generateMipMaps = generateMipMaps;
  18181. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  18182. if (isCube) {
  18183. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18184. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  18185. this._textureMatrix = BABYLON.Matrix.Identity();
  18186. }
  18187. else {
  18188. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  18189. }
  18190. // Rendering groups
  18191. this._renderingManager = new BABYLON.RenderingManager(scene);
  18192. }
  18193. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  18194. get: function () {
  18195. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  18196. },
  18197. enumerable: true,
  18198. configurable: true
  18199. });
  18200. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  18201. get: function () {
  18202. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  18203. },
  18204. enumerable: true,
  18205. configurable: true
  18206. });
  18207. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  18208. get: function () {
  18209. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  18210. },
  18211. enumerable: true,
  18212. configurable: true
  18213. });
  18214. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  18215. this._currentRefreshId = -1;
  18216. };
  18217. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  18218. get: function () {
  18219. return this._refreshRate;
  18220. },
  18221. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18222. set: function (value) {
  18223. this._refreshRate = value;
  18224. this.resetRefreshCounter();
  18225. },
  18226. enumerable: true,
  18227. configurable: true
  18228. });
  18229. RenderTargetTexture.prototype._shouldRender = function () {
  18230. if (this._currentRefreshId === -1) {
  18231. this._currentRefreshId = 1;
  18232. return true;
  18233. }
  18234. if (this.refreshRate === this._currentRefreshId) {
  18235. this._currentRefreshId = 1;
  18236. return true;
  18237. }
  18238. this._currentRefreshId++;
  18239. return false;
  18240. };
  18241. RenderTargetTexture.prototype.isReady = function () {
  18242. if (!this.getScene().renderTargetsEnabled) {
  18243. return false;
  18244. }
  18245. return _super.prototype.isReady.call(this);
  18246. };
  18247. RenderTargetTexture.prototype.getRenderSize = function () {
  18248. return this._size;
  18249. };
  18250. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  18251. get: function () {
  18252. return true;
  18253. },
  18254. enumerable: true,
  18255. configurable: true
  18256. });
  18257. RenderTargetTexture.prototype.scale = function (ratio) {
  18258. var newSize = this._size * ratio;
  18259. this.resize(newSize, this._generateMipMaps);
  18260. };
  18261. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  18262. if (this.isCube) {
  18263. return this._textureMatrix;
  18264. }
  18265. return _super.prototype.getReflectionTextureMatrix.call(this);
  18266. };
  18267. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  18268. this.releaseInternalTexture();
  18269. if (this.isCube) {
  18270. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  18271. }
  18272. else {
  18273. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18274. }
  18275. };
  18276. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  18277. var scene = this.getScene();
  18278. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18279. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  18280. }
  18281. if (this._waitingRenderList) {
  18282. this.renderList = [];
  18283. for (var index = 0; index < this._waitingRenderList.length; index++) {
  18284. var id = this._waitingRenderList[index];
  18285. this.renderList.push(scene.getMeshByID(id));
  18286. }
  18287. delete this._waitingRenderList;
  18288. }
  18289. if (this.renderList && this.renderList.length === 0) {
  18290. return;
  18291. }
  18292. // Prepare renderingManager
  18293. this._renderingManager.reset();
  18294. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  18295. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  18296. var mesh = currentRenderList[meshIndex];
  18297. if (mesh) {
  18298. if (!mesh.isReady()) {
  18299. // Reset _currentRefreshId
  18300. this.resetRefreshCounter();
  18301. continue;
  18302. }
  18303. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  18304. mesh._activate(scene.getRenderId());
  18305. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18306. var subMesh = mesh.subMeshes[subIndex];
  18307. scene._activeIndices += subMesh.indexCount;
  18308. this._renderingManager.dispatch(subMesh);
  18309. }
  18310. }
  18311. }
  18312. }
  18313. if (this.isCube) {
  18314. for (var face = 0; face < 6; face++) {
  18315. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  18316. scene.incrementRenderId();
  18317. }
  18318. }
  18319. else {
  18320. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  18321. }
  18322. if (this.onAfterUnbind) {
  18323. this.onAfterUnbind();
  18324. }
  18325. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18326. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  18327. }
  18328. scene.resetCachedMaterial();
  18329. };
  18330. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  18331. var scene = this.getScene();
  18332. var engine = scene.getEngine();
  18333. // Bind
  18334. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  18335. if (this.isCube) {
  18336. engine.bindFramebuffer(this._texture, faceIndex);
  18337. }
  18338. else {
  18339. engine.bindFramebuffer(this._texture);
  18340. }
  18341. }
  18342. if (this.onBeforeRender) {
  18343. this.onBeforeRender(faceIndex);
  18344. }
  18345. // Clear
  18346. if (this.onClear) {
  18347. this.onClear(engine);
  18348. }
  18349. else {
  18350. engine.clear(scene.clearColor, true, true);
  18351. }
  18352. if (!this._doNotChangeAspectRatio) {
  18353. scene.updateTransformMatrix(true);
  18354. }
  18355. // Render
  18356. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  18357. if (useCameraPostProcess) {
  18358. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18359. }
  18360. if (!this._doNotChangeAspectRatio) {
  18361. scene.updateTransformMatrix(true);
  18362. }
  18363. if (this.onAfterRender) {
  18364. this.onAfterRender(faceIndex);
  18365. }
  18366. // Dump ?
  18367. if (dumpForDebug) {
  18368. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18369. }
  18370. // Unbind
  18371. if (!this.isCube || faceIndex === 5) {
  18372. if (this.isCube) {
  18373. if (faceIndex === 5) {
  18374. engine.generateMipMapsForCubemap(this._texture);
  18375. }
  18376. }
  18377. engine.unBindFramebuffer(this._texture, this.isCube);
  18378. }
  18379. };
  18380. RenderTargetTexture.prototype.clone = function () {
  18381. var textureSize = this.getSize();
  18382. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18383. // Base texture
  18384. newTexture.hasAlpha = this.hasAlpha;
  18385. newTexture.level = this.level;
  18386. // RenderTarget Texture
  18387. newTexture.coordinatesMode = this.coordinatesMode;
  18388. newTexture.renderList = this.renderList.slice(0);
  18389. return newTexture;
  18390. };
  18391. RenderTargetTexture.prototype.serialize = function () {
  18392. if (!this.name) {
  18393. return null;
  18394. }
  18395. var serializationObject = _super.prototype.serialize.call(this);
  18396. serializationObject.renderTargetSize = this.getRenderSize();
  18397. serializationObject.renderList = [];
  18398. for (var index = 0; index < this.renderList.length; index++) {
  18399. serializationObject.renderList.push(this.renderList[index].id);
  18400. }
  18401. return serializationObject;
  18402. };
  18403. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18404. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18405. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18406. return RenderTargetTexture;
  18407. })(BABYLON.Texture);
  18408. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18409. })(BABYLON || (BABYLON = {}));
  18410. var BABYLON;
  18411. (function (BABYLON) {
  18412. var ProceduralTexture = (function (_super) {
  18413. __extends(ProceduralTexture, _super);
  18414. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18415. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18416. if (isCube === void 0) { isCube = false; }
  18417. _super.call(this, null, scene, !generateMipMaps);
  18418. this.isCube = isCube;
  18419. this.isEnabled = true;
  18420. this._currentRefreshId = -1;
  18421. this._refreshRate = 1;
  18422. this._vertexDeclaration = [2];
  18423. this._vertexStrideSize = 2 * 4;
  18424. this._uniforms = new Array();
  18425. this._samplers = new Array();
  18426. this._textures = new Array();
  18427. this._floats = new Array();
  18428. this._floatsArrays = {};
  18429. this._colors3 = new Array();
  18430. this._colors4 = new Array();
  18431. this._vectors2 = new Array();
  18432. this._vectors3 = new Array();
  18433. this._matrices = new Array();
  18434. this._fallbackTextureUsed = false;
  18435. scene._proceduralTextures.push(this);
  18436. this.name = name;
  18437. this.isRenderTarget = true;
  18438. this._size = size;
  18439. this._generateMipMaps = generateMipMaps;
  18440. this.setFragment(fragment);
  18441. this._fallbackTexture = fallbackTexture;
  18442. if (isCube) {
  18443. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18444. this.setFloat("face", 0);
  18445. }
  18446. else {
  18447. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18448. }
  18449. // VBO
  18450. var vertices = [];
  18451. vertices.push(1, 1);
  18452. vertices.push(-1, 1);
  18453. vertices.push(-1, -1);
  18454. vertices.push(1, -1);
  18455. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18456. // Indices
  18457. var indices = [];
  18458. indices.push(0);
  18459. indices.push(1);
  18460. indices.push(2);
  18461. indices.push(0);
  18462. indices.push(2);
  18463. indices.push(3);
  18464. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18465. }
  18466. ProceduralTexture.prototype.reset = function () {
  18467. if (this._effect === undefined) {
  18468. return;
  18469. }
  18470. var engine = this.getScene().getEngine();
  18471. engine._releaseEffect(this._effect);
  18472. };
  18473. ProceduralTexture.prototype.isReady = function () {
  18474. var _this = this;
  18475. var engine = this.getScene().getEngine();
  18476. var shaders;
  18477. if (!this._fragment) {
  18478. return false;
  18479. }
  18480. if (this._fallbackTextureUsed) {
  18481. return true;
  18482. }
  18483. if (this._fragment.fragmentElement !== undefined) {
  18484. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18485. }
  18486. else {
  18487. shaders = { vertex: "procedural", fragment: this._fragment };
  18488. }
  18489. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18490. _this.releaseInternalTexture();
  18491. if (_this._fallbackTexture) {
  18492. _this._texture = _this._fallbackTexture._texture;
  18493. _this._texture.references++;
  18494. }
  18495. _this._fallbackTextureUsed = true;
  18496. });
  18497. return this._effect.isReady();
  18498. };
  18499. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18500. this._currentRefreshId = -1;
  18501. };
  18502. ProceduralTexture.prototype.setFragment = function (fragment) {
  18503. this._fragment = fragment;
  18504. };
  18505. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18506. get: function () {
  18507. return this._refreshRate;
  18508. },
  18509. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18510. set: function (value) {
  18511. this._refreshRate = value;
  18512. this.resetRefreshCounter();
  18513. },
  18514. enumerable: true,
  18515. configurable: true
  18516. });
  18517. ProceduralTexture.prototype._shouldRender = function () {
  18518. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18519. return false;
  18520. }
  18521. if (this._fallbackTextureUsed) {
  18522. return false;
  18523. }
  18524. if (this._currentRefreshId === -1) {
  18525. this._currentRefreshId = 1;
  18526. return true;
  18527. }
  18528. if (this.refreshRate === this._currentRefreshId) {
  18529. this._currentRefreshId = 1;
  18530. return true;
  18531. }
  18532. this._currentRefreshId++;
  18533. return false;
  18534. };
  18535. ProceduralTexture.prototype.getRenderSize = function () {
  18536. return this._size;
  18537. };
  18538. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18539. if (this._fallbackTextureUsed) {
  18540. return;
  18541. }
  18542. this.releaseInternalTexture();
  18543. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18544. };
  18545. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18546. if (this._uniforms.indexOf(uniformName) === -1) {
  18547. this._uniforms.push(uniformName);
  18548. }
  18549. };
  18550. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18551. if (this._samplers.indexOf(name) === -1) {
  18552. this._samplers.push(name);
  18553. }
  18554. this._textures[name] = texture;
  18555. return this;
  18556. };
  18557. ProceduralTexture.prototype.setFloat = function (name, value) {
  18558. this._checkUniform(name);
  18559. this._floats[name] = value;
  18560. return this;
  18561. };
  18562. ProceduralTexture.prototype.setFloats = function (name, value) {
  18563. this._checkUniform(name);
  18564. this._floatsArrays[name] = value;
  18565. return this;
  18566. };
  18567. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18568. this._checkUniform(name);
  18569. this._colors3[name] = value;
  18570. return this;
  18571. };
  18572. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18573. this._checkUniform(name);
  18574. this._colors4[name] = value;
  18575. return this;
  18576. };
  18577. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18578. this._checkUniform(name);
  18579. this._vectors2[name] = value;
  18580. return this;
  18581. };
  18582. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18583. this._checkUniform(name);
  18584. this._vectors3[name] = value;
  18585. return this;
  18586. };
  18587. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18588. this._checkUniform(name);
  18589. this._matrices[name] = value;
  18590. return this;
  18591. };
  18592. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18593. var scene = this.getScene();
  18594. var engine = scene.getEngine();
  18595. // Render
  18596. engine.enableEffect(this._effect);
  18597. engine.setState(false);
  18598. // Texture
  18599. for (var name in this._textures) {
  18600. this._effect.setTexture(name, this._textures[name]);
  18601. }
  18602. // Float
  18603. for (name in this._floats) {
  18604. this._effect.setFloat(name, this._floats[name]);
  18605. }
  18606. // Floats
  18607. for (name in this._floatsArrays) {
  18608. this._effect.setArray(name, this._floatsArrays[name]);
  18609. }
  18610. // Color3
  18611. for (name in this._colors3) {
  18612. this._effect.setColor3(name, this._colors3[name]);
  18613. }
  18614. // Color4
  18615. for (name in this._colors4) {
  18616. var color = this._colors4[name];
  18617. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18618. }
  18619. // Vector2
  18620. for (name in this._vectors2) {
  18621. this._effect.setVector2(name, this._vectors2[name]);
  18622. }
  18623. // Vector3
  18624. for (name in this._vectors3) {
  18625. this._effect.setVector3(name, this._vectors3[name]);
  18626. }
  18627. // Matrix
  18628. for (name in this._matrices) {
  18629. this._effect.setMatrix(name, this._matrices[name]);
  18630. }
  18631. // VBOs
  18632. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18633. if (this.isCube) {
  18634. for (var face = 0; face < 6; face++) {
  18635. engine.bindFramebuffer(this._texture, face);
  18636. this._effect.setFloat("face", face);
  18637. // Clear
  18638. engine.clear(scene.clearColor, true, true);
  18639. // Draw order
  18640. engine.draw(true, 0, 6);
  18641. // Mipmaps
  18642. if (face === 5) {
  18643. engine.generateMipMapsForCubemap(this._texture);
  18644. }
  18645. }
  18646. }
  18647. else {
  18648. engine.bindFramebuffer(this._texture);
  18649. // Clear
  18650. engine.clear(scene.clearColor, true, true);
  18651. // Draw order
  18652. engine.draw(true, 0, 6);
  18653. }
  18654. // Unbind
  18655. engine.unBindFramebuffer(this._texture, this.isCube);
  18656. if (this.onGenerated) {
  18657. this.onGenerated();
  18658. }
  18659. };
  18660. ProceduralTexture.prototype.clone = function () {
  18661. var textureSize = this.getSize();
  18662. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18663. // Base texture
  18664. newTexture.hasAlpha = this.hasAlpha;
  18665. newTexture.level = this.level;
  18666. // RenderTarget Texture
  18667. newTexture.coordinatesMode = this.coordinatesMode;
  18668. return newTexture;
  18669. };
  18670. ProceduralTexture.prototype.dispose = function () {
  18671. var index = this.getScene()._proceduralTextures.indexOf(this);
  18672. if (index >= 0) {
  18673. this.getScene()._proceduralTextures.splice(index, 1);
  18674. }
  18675. _super.prototype.dispose.call(this);
  18676. };
  18677. return ProceduralTexture;
  18678. })(BABYLON.Texture);
  18679. BABYLON.ProceduralTexture = ProceduralTexture;
  18680. })(BABYLON || (BABYLON = {}));
  18681. var BABYLON;
  18682. (function (BABYLON) {
  18683. var MirrorTexture = (function (_super) {
  18684. __extends(MirrorTexture, _super);
  18685. function MirrorTexture(name, size, scene, generateMipMaps) {
  18686. var _this = this;
  18687. _super.call(this, name, size, scene, generateMipMaps, true);
  18688. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18689. this._transformMatrix = BABYLON.Matrix.Zero();
  18690. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18691. this.onBeforeRender = function () {
  18692. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18693. _this._savedViewMatrix = scene.getViewMatrix();
  18694. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18695. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18696. scene.clipPlane = _this.mirrorPlane;
  18697. scene.getEngine().cullBackFaces = false;
  18698. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18699. };
  18700. this.onAfterRender = function () {
  18701. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18702. scene.getEngine().cullBackFaces = true;
  18703. scene._mirroredCameraPosition = null;
  18704. delete scene.clipPlane;
  18705. };
  18706. }
  18707. MirrorTexture.prototype.clone = function () {
  18708. var textureSize = this.getSize();
  18709. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18710. // Base texture
  18711. newTexture.hasAlpha = this.hasAlpha;
  18712. newTexture.level = this.level;
  18713. // Mirror Texture
  18714. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18715. newTexture.renderList = this.renderList.slice(0);
  18716. return newTexture;
  18717. };
  18718. MirrorTexture.prototype.serialize = function () {
  18719. if (!this.name) {
  18720. return null;
  18721. }
  18722. var serializationObject = _super.prototype.serialize.call(this);
  18723. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18724. return serializationObject;
  18725. };
  18726. return MirrorTexture;
  18727. })(BABYLON.RenderTargetTexture);
  18728. BABYLON.MirrorTexture = MirrorTexture;
  18729. })(BABYLON || (BABYLON = {}));
  18730. var BABYLON;
  18731. (function (BABYLON) {
  18732. /**
  18733. * Creates a refraction texture used by refraction channel of the standard material.
  18734. * @param name the texture name
  18735. * @param size size of the underlying texture
  18736. * @param scene root scene
  18737. */
  18738. var RefractionTexture = (function (_super) {
  18739. __extends(RefractionTexture, _super);
  18740. function RefractionTexture(name, size, scene, generateMipMaps) {
  18741. var _this = this;
  18742. _super.call(this, name, size, scene, generateMipMaps, true);
  18743. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18744. this.depth = 2.0;
  18745. this.onBeforeRender = function () {
  18746. scene.clipPlane = _this.refractionPlane;
  18747. };
  18748. this.onAfterRender = function () {
  18749. delete scene.clipPlane;
  18750. };
  18751. }
  18752. RefractionTexture.prototype.clone = function () {
  18753. var textureSize = this.getSize();
  18754. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18755. // Base texture
  18756. newTexture.hasAlpha = this.hasAlpha;
  18757. newTexture.level = this.level;
  18758. // Refraction Texture
  18759. newTexture.refractionPlane = this.refractionPlane.clone();
  18760. newTexture.renderList = this.renderList.slice(0);
  18761. newTexture.depth = this.depth;
  18762. return newTexture;
  18763. };
  18764. RefractionTexture.prototype.serialize = function () {
  18765. if (!this.name) {
  18766. return null;
  18767. }
  18768. var serializationObject = _super.prototype.serialize.call(this);
  18769. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18770. serializationObject.depth = this.depth;
  18771. return serializationObject;
  18772. };
  18773. return RefractionTexture;
  18774. })(BABYLON.RenderTargetTexture);
  18775. BABYLON.RefractionTexture = RefractionTexture;
  18776. })(BABYLON || (BABYLON = {}));
  18777. var BABYLON;
  18778. (function (BABYLON) {
  18779. var DynamicTexture = (function (_super) {
  18780. __extends(DynamicTexture, _super);
  18781. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18783. _super.call(this, null, scene, !generateMipMaps);
  18784. this.name = name;
  18785. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18786. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18787. this._generateMipMaps = generateMipMaps;
  18788. if (options.getContext) {
  18789. this._canvas = options;
  18790. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18791. }
  18792. else {
  18793. this._canvas = document.createElement("canvas");
  18794. if (options.width) {
  18795. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18796. }
  18797. else {
  18798. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18799. }
  18800. }
  18801. var textureSize = this.getSize();
  18802. this._canvas.width = textureSize.width;
  18803. this._canvas.height = textureSize.height;
  18804. this._context = this._canvas.getContext("2d");
  18805. }
  18806. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18807. get: function () {
  18808. return true;
  18809. },
  18810. enumerable: true,
  18811. configurable: true
  18812. });
  18813. DynamicTexture.prototype.scale = function (ratio) {
  18814. var textureSize = this.getSize();
  18815. textureSize.width *= ratio;
  18816. textureSize.height *= ratio;
  18817. this._canvas.width = textureSize.width;
  18818. this._canvas.height = textureSize.height;
  18819. this.releaseInternalTexture();
  18820. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18821. };
  18822. DynamicTexture.prototype.getContext = function () {
  18823. return this._context;
  18824. };
  18825. DynamicTexture.prototype.clear = function () {
  18826. var size = this.getSize();
  18827. this._context.fillRect(0, 0, size.width, size.height);
  18828. };
  18829. DynamicTexture.prototype.update = function (invertY) {
  18830. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18831. };
  18832. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18833. if (update === void 0) { update = true; }
  18834. var size = this.getSize();
  18835. if (clearColor) {
  18836. this._context.fillStyle = clearColor;
  18837. this._context.fillRect(0, 0, size.width, size.height);
  18838. }
  18839. this._context.font = font;
  18840. if (x === null) {
  18841. var textSize = this._context.measureText(text);
  18842. x = (size.width - textSize.width) / 2;
  18843. }
  18844. this._context.fillStyle = color;
  18845. this._context.fillText(text, x, y);
  18846. if (update) {
  18847. this.update(invertY);
  18848. }
  18849. };
  18850. DynamicTexture.prototype.clone = function () {
  18851. var textureSize = this.getSize();
  18852. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18853. // Base texture
  18854. newTexture.hasAlpha = this.hasAlpha;
  18855. newTexture.level = this.level;
  18856. // Dynamic Texture
  18857. newTexture.wrapU = this.wrapU;
  18858. newTexture.wrapV = this.wrapV;
  18859. return newTexture;
  18860. };
  18861. return DynamicTexture;
  18862. })(BABYLON.Texture);
  18863. BABYLON.DynamicTexture = DynamicTexture;
  18864. })(BABYLON || (BABYLON = {}));
  18865. var BABYLON;
  18866. (function (BABYLON) {
  18867. var VideoTexture = (function (_super) {
  18868. __extends(VideoTexture, _super);
  18869. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18870. var _this = this;
  18871. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18872. if (invertY === void 0) { invertY = false; }
  18873. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18874. _super.call(this, null, scene, !generateMipMaps, invertY);
  18875. this._autoLaunch = true;
  18876. this.name = name;
  18877. this.video = document.createElement("video");
  18878. this.video.autoplay = false;
  18879. this.video.loop = true;
  18880. this.video.addEventListener("canplaythrough", function () {
  18881. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18882. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18883. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18884. }
  18885. else {
  18886. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18887. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18888. generateMipMaps = false;
  18889. }
  18890. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18891. _this._texture.isReady = true;
  18892. });
  18893. urls.forEach(function (url) {
  18894. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18895. var source = document.createElement("source");
  18896. source.src = url;
  18897. _this.video.appendChild(source);
  18898. });
  18899. this._lastUpdate = BABYLON.Tools.Now;
  18900. }
  18901. VideoTexture.prototype.update = function () {
  18902. if (this._autoLaunch) {
  18903. this._autoLaunch = false;
  18904. this.video.play();
  18905. }
  18906. var now = BABYLON.Tools.Now;
  18907. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18908. return false;
  18909. }
  18910. this._lastUpdate = now;
  18911. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18912. return true;
  18913. };
  18914. return VideoTexture;
  18915. })(BABYLON.Texture);
  18916. BABYLON.VideoTexture = VideoTexture;
  18917. })(BABYLON || (BABYLON = {}));
  18918. var BABYLON;
  18919. (function (BABYLON) {
  18920. var CustomProceduralTexture = (function (_super) {
  18921. __extends(CustomProceduralTexture, _super);
  18922. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18923. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18924. this._animate = true;
  18925. this._time = 0;
  18926. this._texturePath = texturePath;
  18927. //Try to load json
  18928. this.loadJson(texturePath);
  18929. this.refreshRate = 1;
  18930. }
  18931. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18932. var _this = this;
  18933. var that = this;
  18934. function noConfigFile() {
  18935. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18936. try {
  18937. that.setFragment(that._texturePath);
  18938. }
  18939. catch (ex) {
  18940. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18941. }
  18942. }
  18943. var configFileUrl = jsonUrl + "/config.json";
  18944. var xhr = new XMLHttpRequest();
  18945. xhr.open("GET", configFileUrl, true);
  18946. xhr.addEventListener("load", function () {
  18947. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18948. try {
  18949. _this._config = JSON.parse(xhr.response);
  18950. _this.updateShaderUniforms();
  18951. _this.updateTextures();
  18952. _this.setFragment(_this._texturePath + "/custom");
  18953. _this._animate = _this._config.animate;
  18954. _this.refreshRate = _this._config.refreshrate;
  18955. }
  18956. catch (ex) {
  18957. noConfigFile();
  18958. }
  18959. }
  18960. else {
  18961. noConfigFile();
  18962. }
  18963. }, false);
  18964. xhr.addEventListener("error", function () {
  18965. noConfigFile();
  18966. }, false);
  18967. try {
  18968. xhr.send();
  18969. }
  18970. catch (ex) {
  18971. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18972. }
  18973. };
  18974. CustomProceduralTexture.prototype.isReady = function () {
  18975. if (!_super.prototype.isReady.call(this)) {
  18976. return false;
  18977. }
  18978. for (var name in this._textures) {
  18979. var texture = this._textures[name];
  18980. if (!texture.isReady()) {
  18981. return false;
  18982. }
  18983. }
  18984. return true;
  18985. };
  18986. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18987. if (this._animate) {
  18988. this._time += this.getScene().getAnimationRatio() * 0.03;
  18989. this.updateShaderUniforms();
  18990. }
  18991. _super.prototype.render.call(this, useCameraPostProcess);
  18992. };
  18993. CustomProceduralTexture.prototype.updateTextures = function () {
  18994. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18995. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18996. }
  18997. };
  18998. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18999. if (this._config) {
  19000. for (var j = 0; j < this._config.uniforms.length; j++) {
  19001. var uniform = this._config.uniforms[j];
  19002. switch (uniform.type) {
  19003. case "float":
  19004. this.setFloat(uniform.name, uniform.value);
  19005. break;
  19006. case "color3":
  19007. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  19008. break;
  19009. case "color4":
  19010. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  19011. break;
  19012. case "vector2":
  19013. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  19014. break;
  19015. case "vector3":
  19016. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  19017. break;
  19018. }
  19019. }
  19020. }
  19021. this.setFloat("time", this._time);
  19022. };
  19023. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  19024. get: function () {
  19025. return this._animate;
  19026. },
  19027. set: function (value) {
  19028. this._animate = value;
  19029. },
  19030. enumerable: true,
  19031. configurable: true
  19032. });
  19033. return CustomProceduralTexture;
  19034. })(BABYLON.ProceduralTexture);
  19035. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  19036. })(BABYLON || (BABYLON = {}));
  19037. var BABYLON;
  19038. (function (BABYLON) {
  19039. var EffectFallbacks = (function () {
  19040. function EffectFallbacks() {
  19041. this._defines = {};
  19042. this._currentRank = 32;
  19043. this._maxRank = -1;
  19044. }
  19045. EffectFallbacks.prototype.addFallback = function (rank, define) {
  19046. if (!this._defines[rank]) {
  19047. if (rank < this._currentRank) {
  19048. this._currentRank = rank;
  19049. }
  19050. if (rank > this._maxRank) {
  19051. this._maxRank = rank;
  19052. }
  19053. this._defines[rank] = new Array();
  19054. }
  19055. this._defines[rank].push(define);
  19056. };
  19057. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  19058. this._meshRank = rank;
  19059. this._mesh = mesh;
  19060. if (rank > this._maxRank) {
  19061. this._maxRank = rank;
  19062. }
  19063. };
  19064. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  19065. get: function () {
  19066. return this._currentRank <= this._maxRank;
  19067. },
  19068. enumerable: true,
  19069. configurable: true
  19070. });
  19071. EffectFallbacks.prototype.reduce = function (currentDefines) {
  19072. var currentFallbacks = this._defines[this._currentRank];
  19073. for (var index = 0; index < currentFallbacks.length; index++) {
  19074. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  19075. }
  19076. if (this._mesh && this._currentRank === this._meshRank) {
  19077. this._mesh.computeBonesUsingShaders = false;
  19078. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  19079. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  19080. }
  19081. this._currentRank++;
  19082. return currentDefines;
  19083. };
  19084. return EffectFallbacks;
  19085. })();
  19086. BABYLON.EffectFallbacks = EffectFallbacks;
  19087. var Effect = (function () {
  19088. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  19089. var _this = this;
  19090. this._isReady = false;
  19091. this._compilationError = "";
  19092. this._valueCache = [];
  19093. this._engine = engine;
  19094. this.name = baseName;
  19095. this.defines = defines;
  19096. this._uniformsNames = uniformsNames.concat(samplers);
  19097. this._samplers = samplers;
  19098. this._attributesNames = attributesNames;
  19099. this.onError = onError;
  19100. this.onCompiled = onCompiled;
  19101. var vertexSource;
  19102. var fragmentSource;
  19103. if (baseName.vertexElement) {
  19104. vertexSource = document.getElementById(baseName.vertexElement);
  19105. if (!vertexSource) {
  19106. vertexSource = baseName.vertexElement;
  19107. }
  19108. }
  19109. else {
  19110. vertexSource = baseName.vertex || baseName;
  19111. }
  19112. if (baseName.fragmentElement) {
  19113. fragmentSource = document.getElementById(baseName.fragmentElement);
  19114. if (!fragmentSource) {
  19115. fragmentSource = baseName.fragmentElement;
  19116. }
  19117. }
  19118. else {
  19119. fragmentSource = baseName.fragment || baseName;
  19120. }
  19121. this._loadVertexShader(vertexSource, function (vertexCode) {
  19122. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  19123. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  19124. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  19125. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  19126. });
  19127. });
  19128. });
  19129. });
  19130. }
  19131. // Properties
  19132. Effect.prototype.isReady = function () {
  19133. return this._isReady;
  19134. };
  19135. Effect.prototype.getProgram = function () {
  19136. return this._program;
  19137. };
  19138. Effect.prototype.getAttributesNames = function () {
  19139. return this._attributesNames;
  19140. };
  19141. Effect.prototype.getAttributeLocation = function (index) {
  19142. return this._attributes[index];
  19143. };
  19144. Effect.prototype.getAttributeLocationByName = function (name) {
  19145. var index = this._attributesNames.indexOf(name);
  19146. return this._attributes[index];
  19147. };
  19148. Effect.prototype.getAttributesCount = function () {
  19149. return this._attributes.length;
  19150. };
  19151. Effect.prototype.getUniformIndex = function (uniformName) {
  19152. return this._uniformsNames.indexOf(uniformName);
  19153. };
  19154. Effect.prototype.getUniform = function (uniformName) {
  19155. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  19156. };
  19157. Effect.prototype.getSamplers = function () {
  19158. return this._samplers;
  19159. };
  19160. Effect.prototype.getCompilationError = function () {
  19161. return this._compilationError;
  19162. };
  19163. // Methods
  19164. Effect.prototype._loadVertexShader = function (vertex, callback) {
  19165. // DOM element ?
  19166. if (vertex instanceof HTMLElement) {
  19167. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  19168. callback(vertexCode);
  19169. return;
  19170. }
  19171. // Is in local store ?
  19172. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  19173. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  19174. return;
  19175. }
  19176. var vertexShaderUrl;
  19177. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  19178. vertexShaderUrl = vertex;
  19179. }
  19180. else {
  19181. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  19182. }
  19183. // Vertex shader
  19184. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  19185. };
  19186. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  19187. // DOM element ?
  19188. if (fragment instanceof HTMLElement) {
  19189. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  19190. callback(fragmentCode);
  19191. return;
  19192. }
  19193. // Is in local store ?
  19194. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  19195. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  19196. return;
  19197. }
  19198. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  19199. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  19200. return;
  19201. }
  19202. var fragmentShaderUrl;
  19203. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  19204. fragmentShaderUrl = fragment;
  19205. }
  19206. else {
  19207. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  19208. }
  19209. // Fragment shader
  19210. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  19211. };
  19212. Effect.prototype._dumpShadersName = function () {
  19213. if (this.name.vertexElement) {
  19214. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  19215. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  19216. }
  19217. else if (this.name.vertex) {
  19218. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  19219. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  19220. }
  19221. else {
  19222. BABYLON.Tools.Error("Vertex shader:" + this.name);
  19223. BABYLON.Tools.Error("Fragment shader:" + this.name);
  19224. }
  19225. };
  19226. Effect.prototype._processIncludes = function (sourceCode, callback) {
  19227. var _this = this;
  19228. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  19229. var match = regex.exec(sourceCode);
  19230. var returnValue = new String(sourceCode);
  19231. while (match != null) {
  19232. var includeFile = match[1];
  19233. if (Effect.IncludesShadersStore[includeFile]) {
  19234. // Substitution
  19235. var includeContent = Effect.IncludesShadersStore[includeFile];
  19236. if (match[2]) {
  19237. var splits = match[3].split(",");
  19238. for (var index = 0; index < splits.length; index += 2) {
  19239. var source = new RegExp(splits[index], "g");
  19240. var dest = splits[index + 1];
  19241. includeContent = includeContent.replace(source, dest);
  19242. }
  19243. }
  19244. if (match[4]) {
  19245. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  19246. }
  19247. // Replace
  19248. returnValue = returnValue.replace(match[0], includeContent);
  19249. }
  19250. else {
  19251. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  19252. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  19253. Effect.IncludesShadersStore[includeFile] = fileContent;
  19254. _this._processIncludes(returnValue, callback);
  19255. });
  19256. return;
  19257. }
  19258. match = regex.exec(sourceCode);
  19259. }
  19260. callback(returnValue);
  19261. };
  19262. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  19263. try {
  19264. var engine = this._engine;
  19265. // Precision
  19266. if (!engine.getCaps().highPrecisionShaderSupported) {
  19267. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19268. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19269. }
  19270. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  19271. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  19272. this._attributes = engine.getAttributes(this._program, attributesNames);
  19273. for (var index = 0; index < this._samplers.length; index++) {
  19274. var sampler = this.getUniform(this._samplers[index]);
  19275. if (sampler == null) {
  19276. this._samplers.splice(index, 1);
  19277. index--;
  19278. }
  19279. }
  19280. engine.bindSamplers(this);
  19281. this._isReady = true;
  19282. if (this.onCompiled) {
  19283. this.onCompiled(this);
  19284. }
  19285. }
  19286. catch (e) {
  19287. // Is it a problem with precision?
  19288. if (e.message.indexOf("highp") !== -1) {
  19289. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19290. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19291. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19292. return;
  19293. }
  19294. // Let's go through fallbacks then
  19295. if (fallbacks && fallbacks.isMoreFallbacks) {
  19296. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  19297. this._dumpShadersName();
  19298. defines = fallbacks.reduce(defines);
  19299. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19300. }
  19301. else {
  19302. BABYLON.Tools.Error("Unable to compile effect: ");
  19303. this._dumpShadersName();
  19304. BABYLON.Tools.Error("Defines: " + defines);
  19305. BABYLON.Tools.Error("Error: " + e.message);
  19306. this._compilationError = e.message;
  19307. if (this.onError) {
  19308. this.onError(this, this._compilationError);
  19309. }
  19310. }
  19311. }
  19312. };
  19313. Object.defineProperty(Effect.prototype, "isSupported", {
  19314. get: function () {
  19315. return this._compilationError === "";
  19316. },
  19317. enumerable: true,
  19318. configurable: true
  19319. });
  19320. Effect.prototype._bindTexture = function (channel, texture) {
  19321. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  19322. };
  19323. Effect.prototype.setTexture = function (channel, texture) {
  19324. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  19325. };
  19326. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  19327. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  19328. };
  19329. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  19330. if (!this._valueCache[uniformName]) {
  19331. this._valueCache[uniformName] = new BABYLON.Matrix();
  19332. }
  19333. for (var index = 0; index < 16; index++) {
  19334. this._valueCache[uniformName].m[index] = matrix.m[index];
  19335. }
  19336. };
  19337. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  19338. if (!this._valueCache[uniformName]) {
  19339. this._valueCache[uniformName] = [x, y];
  19340. return;
  19341. }
  19342. this._valueCache[uniformName][0] = x;
  19343. this._valueCache[uniformName][1] = y;
  19344. };
  19345. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  19346. if (!this._valueCache[uniformName]) {
  19347. this._valueCache[uniformName] = [x, y, z];
  19348. return;
  19349. }
  19350. this._valueCache[uniformName][0] = x;
  19351. this._valueCache[uniformName][1] = y;
  19352. this._valueCache[uniformName][2] = z;
  19353. };
  19354. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  19355. if (!this._valueCache[uniformName]) {
  19356. this._valueCache[uniformName] = [x, y, z, w];
  19357. return;
  19358. }
  19359. this._valueCache[uniformName][0] = x;
  19360. this._valueCache[uniformName][1] = y;
  19361. this._valueCache[uniformName][2] = z;
  19362. this._valueCache[uniformName][3] = w;
  19363. };
  19364. Effect.prototype.setArray = function (uniformName, array) {
  19365. this._engine.setArray(this.getUniform(uniformName), array);
  19366. return this;
  19367. };
  19368. Effect.prototype.setArray2 = function (uniformName, array) {
  19369. this._engine.setArray2(this.getUniform(uniformName), array);
  19370. return this;
  19371. };
  19372. Effect.prototype.setArray3 = function (uniformName, array) {
  19373. this._engine.setArray3(this.getUniform(uniformName), array);
  19374. return this;
  19375. };
  19376. Effect.prototype.setArray4 = function (uniformName, array) {
  19377. this._engine.setArray4(this.getUniform(uniformName), array);
  19378. return this;
  19379. };
  19380. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19381. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19382. return this;
  19383. };
  19384. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19385. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19386. // return this;
  19387. // this._cacheMatrix(uniformName, matrix);
  19388. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19389. return this;
  19390. };
  19391. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19392. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19393. return this;
  19394. };
  19395. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19396. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19397. return this;
  19398. };
  19399. Effect.prototype.setFloat = function (uniformName, value) {
  19400. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19401. return this;
  19402. this._valueCache[uniformName] = value;
  19403. this._engine.setFloat(this.getUniform(uniformName), value);
  19404. return this;
  19405. };
  19406. Effect.prototype.setBool = function (uniformName, bool) {
  19407. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19408. return this;
  19409. this._valueCache[uniformName] = bool;
  19410. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19411. return this;
  19412. };
  19413. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19414. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19415. return this;
  19416. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19417. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19418. return this;
  19419. };
  19420. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19421. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19422. return this;
  19423. this._cacheFloat2(uniformName, x, y);
  19424. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19425. return this;
  19426. };
  19427. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19428. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19429. return this;
  19430. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19431. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19432. return this;
  19433. };
  19434. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19435. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19436. return this;
  19437. this._cacheFloat3(uniformName, x, y, z);
  19438. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19439. return this;
  19440. };
  19441. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19442. 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)
  19443. return this;
  19444. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19445. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19446. return this;
  19447. };
  19448. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19449. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19450. return this;
  19451. this._cacheFloat4(uniformName, x, y, z, w);
  19452. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19453. return this;
  19454. };
  19455. Effect.prototype.setColor3 = function (uniformName, color3) {
  19456. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19457. return this;
  19458. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19459. this._engine.setColor3(this.getUniform(uniformName), color3);
  19460. return this;
  19461. };
  19462. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19463. 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)
  19464. return this;
  19465. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19466. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19467. return this;
  19468. };
  19469. // Statics
  19470. Effect.ShadersStore = {};
  19471. Effect.IncludesShadersStore = {};
  19472. return Effect;
  19473. })();
  19474. BABYLON.Effect = Effect;
  19475. })(BABYLON || (BABYLON = {}));
  19476. var BABYLON;
  19477. (function (BABYLON) {
  19478. var maxSimultaneousLights = 4;
  19479. var MaterialHelper = (function () {
  19480. function MaterialHelper() {
  19481. }
  19482. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  19483. var lightIndex = 0;
  19484. var needNormals = false;
  19485. for (var index = 0; index < scene.lights.length; index++) {
  19486. var light = scene.lights[index];
  19487. if (!light.isEnabled()) {
  19488. continue;
  19489. }
  19490. // Excluded check
  19491. if (light._excludedMeshesIds.length > 0) {
  19492. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19493. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19494. if (excludedMesh) {
  19495. light.excludedMeshes.push(excludedMesh);
  19496. }
  19497. }
  19498. light._excludedMeshesIds = [];
  19499. }
  19500. // Included check
  19501. if (light._includedOnlyMeshesIds.length > 0) {
  19502. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19503. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19504. if (includedOnlyMesh) {
  19505. light.includedOnlyMeshes.push(includedOnlyMesh);
  19506. }
  19507. }
  19508. light._includedOnlyMeshesIds = [];
  19509. }
  19510. if (!light.canAffectMesh(mesh)) {
  19511. continue;
  19512. }
  19513. needNormals = true;
  19514. defines["LIGHT" + lightIndex] = true;
  19515. var type;
  19516. if (light instanceof BABYLON.SpotLight) {
  19517. type = "SPOTLIGHT" + lightIndex;
  19518. }
  19519. else if (light instanceof BABYLON.HemisphericLight) {
  19520. type = "HEMILIGHT" + lightIndex;
  19521. }
  19522. else if (light instanceof BABYLON.PointLight) {
  19523. type = "POINTLIGHT" + lightIndex;
  19524. }
  19525. else {
  19526. type = "DIRLIGHT" + lightIndex;
  19527. }
  19528. defines[type] = true;
  19529. // Specular
  19530. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19531. defines["SPECULARTERM"] = true;
  19532. }
  19533. // Shadows
  19534. if (scene.shadowsEnabled) {
  19535. var shadowGenerator = light.getShadowGenerator();
  19536. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19537. defines["SHADOW" + lightIndex] = true;
  19538. defines["SHADOWS"] = true;
  19539. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19540. defines["SHADOWVSM" + lightIndex] = true;
  19541. }
  19542. if (shadowGenerator.usePoissonSampling) {
  19543. defines["SHADOWPCF" + lightIndex] = true;
  19544. }
  19545. }
  19546. }
  19547. lightIndex++;
  19548. if (lightIndex === maxSimultaneousLights)
  19549. break;
  19550. }
  19551. return needNormals;
  19552. };
  19553. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  19554. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19555. if (!defines["LIGHT" + lightIndex]) {
  19556. continue;
  19557. }
  19558. if (lightIndex > 0) {
  19559. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19560. }
  19561. if (defines["SHADOW" + lightIndex]) {
  19562. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19563. }
  19564. if (defines["SHADOWPCF" + lightIndex]) {
  19565. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19566. }
  19567. if (defines["SHADOWVSM" + lightIndex]) {
  19568. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19569. }
  19570. }
  19571. };
  19572. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19573. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19574. fallbacks.addCPUSkinningFallback(0, mesh);
  19575. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19576. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19577. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19578. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19579. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19580. }
  19581. }
  19582. };
  19583. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  19584. if (defines["INSTANCES"]) {
  19585. attribs.push("world0");
  19586. attribs.push("world1");
  19587. attribs.push("world2");
  19588. attribs.push("world3");
  19589. }
  19590. };
  19591. // Bindings
  19592. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19593. var shadowGenerator = light.getShadowGenerator();
  19594. if (mesh.receiveShadows && shadowGenerator) {
  19595. if (!light.needCube()) {
  19596. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19597. }
  19598. else {
  19599. if (!depthValuesAlreadySet) {
  19600. depthValuesAlreadySet = true;
  19601. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19602. }
  19603. }
  19604. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19605. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19606. }
  19607. return depthValuesAlreadySet;
  19608. };
  19609. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  19610. if (light instanceof BABYLON.PointLight) {
  19611. // Point Light
  19612. light.transferToEffect(effect, "vLightData" + lightIndex);
  19613. }
  19614. else if (light instanceof BABYLON.DirectionalLight) {
  19615. // Directional Light
  19616. light.transferToEffect(effect, "vLightData" + lightIndex);
  19617. }
  19618. else if (light instanceof BABYLON.SpotLight) {
  19619. // Spot Light
  19620. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19621. }
  19622. else if (light instanceof BABYLON.HemisphericLight) {
  19623. // Hemispheric Light
  19624. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19625. }
  19626. };
  19627. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  19628. var lightIndex = 0;
  19629. var depthValuesAlreadySet = false;
  19630. for (var index = 0; index < scene.lights.length; index++) {
  19631. var light = scene.lights[index];
  19632. if (!light.isEnabled()) {
  19633. continue;
  19634. }
  19635. if (!light.canAffectMesh(mesh)) {
  19636. continue;
  19637. }
  19638. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  19639. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  19640. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  19641. if (defines["SPECULARTERM"]) {
  19642. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  19643. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  19644. }
  19645. // Shadows
  19646. if (scene.shadowsEnabled) {
  19647. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19648. }
  19649. lightIndex++;
  19650. if (lightIndex === maxSimultaneousLights)
  19651. break;
  19652. }
  19653. };
  19654. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  19655. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19656. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19657. effect.setColor3("vFogColor", scene.fogColor);
  19658. }
  19659. };
  19660. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  19661. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19662. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19663. }
  19664. };
  19665. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  19666. if (defines["LOGARITHMICDEPTH"]) {
  19667. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19668. }
  19669. };
  19670. MaterialHelper.BindClipPlane = function (effect, scene) {
  19671. if (scene.clipPlane) {
  19672. var clipPlane = scene.clipPlane;
  19673. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19674. }
  19675. };
  19676. return MaterialHelper;
  19677. })();
  19678. BABYLON.MaterialHelper = MaterialHelper;
  19679. })(BABYLON || (BABYLON = {}));
  19680. var BABYLON;
  19681. (function (BABYLON) {
  19682. var FresnelParameters = (function () {
  19683. function FresnelParameters() {
  19684. this.isEnabled = true;
  19685. this.leftColor = BABYLON.Color3.White();
  19686. this.rightColor = BABYLON.Color3.Black();
  19687. this.bias = 0;
  19688. this.power = 1;
  19689. }
  19690. FresnelParameters.prototype.clone = function () {
  19691. var newFresnelParameters = new FresnelParameters();
  19692. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19693. return new FresnelParameters;
  19694. };
  19695. FresnelParameters.prototype.serialize = function () {
  19696. var serializationObject = {};
  19697. serializationObject.isEnabled = this.isEnabled;
  19698. serializationObject.leftColor = this.leftColor;
  19699. serializationObject.rightColor = this.rightColor;
  19700. serializationObject.bias = this.bias;
  19701. serializationObject.power = this.power;
  19702. return serializationObject;
  19703. };
  19704. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19705. var fresnelParameters = new FresnelParameters();
  19706. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19707. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19708. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19709. fresnelParameters.bias = parsedFresnelParameters.bias;
  19710. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19711. return fresnelParameters;
  19712. };
  19713. return FresnelParameters;
  19714. })();
  19715. BABYLON.FresnelParameters = FresnelParameters;
  19716. })(BABYLON || (BABYLON = {}));
  19717. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19718. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19719. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19720. 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;
  19721. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19722. };
  19723. var BABYLON;
  19724. (function (BABYLON) {
  19725. var MaterialDefines = (function () {
  19726. function MaterialDefines() {
  19727. }
  19728. MaterialDefines.prototype.isEqual = function (other) {
  19729. for (var index = 0; index < this._keys.length; index++) {
  19730. var prop = this._keys[index];
  19731. if (this[prop] !== other[prop]) {
  19732. return false;
  19733. }
  19734. }
  19735. return true;
  19736. };
  19737. MaterialDefines.prototype.cloneTo = function (other) {
  19738. for (var index = 0; index < this._keys.length; index++) {
  19739. var prop = this._keys[index];
  19740. other[prop] = this[prop];
  19741. }
  19742. };
  19743. MaterialDefines.prototype.reset = function () {
  19744. for (var index = 0; index < this._keys.length; index++) {
  19745. var prop = this._keys[index];
  19746. if (typeof (this[prop]) === "number") {
  19747. this[prop] = 0;
  19748. }
  19749. else {
  19750. this[prop] = false;
  19751. }
  19752. }
  19753. };
  19754. MaterialDefines.prototype.toString = function () {
  19755. var result = "";
  19756. for (var index = 0; index < this._keys.length; index++) {
  19757. var prop = this._keys[index];
  19758. if (typeof (this[prop]) === "number") {
  19759. result += "#define " + prop + " " + this[prop] + "\n";
  19760. }
  19761. else if (this[prop]) {
  19762. result += "#define " + prop + "\n";
  19763. }
  19764. }
  19765. return result;
  19766. };
  19767. return MaterialDefines;
  19768. })();
  19769. BABYLON.MaterialDefines = MaterialDefines;
  19770. var Material = (function () {
  19771. function Material(name, scene, doNotAdd) {
  19772. this.name = name;
  19773. this.checkReadyOnEveryCall = false;
  19774. this.checkReadyOnlyOnce = false;
  19775. this.state = "";
  19776. this.alpha = 1.0;
  19777. this.backFaceCulling = true;
  19778. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19779. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19780. this.disableDepthWrite = false;
  19781. this.fogEnabled = true;
  19782. this.pointSize = 1.0;
  19783. this.zOffset = 0;
  19784. this._wasPreviouslyReady = false;
  19785. this._fillMode = Material.TriangleFillMode;
  19786. this.id = name;
  19787. this._scene = scene;
  19788. if (!doNotAdd) {
  19789. scene.materials.push(this);
  19790. }
  19791. }
  19792. Object.defineProperty(Material, "TriangleFillMode", {
  19793. get: function () {
  19794. return Material._TriangleFillMode;
  19795. },
  19796. enumerable: true,
  19797. configurable: true
  19798. });
  19799. Object.defineProperty(Material, "WireFrameFillMode", {
  19800. get: function () {
  19801. return Material._WireFrameFillMode;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(Material, "PointFillMode", {
  19807. get: function () {
  19808. return Material._PointFillMode;
  19809. },
  19810. enumerable: true,
  19811. configurable: true
  19812. });
  19813. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19814. get: function () {
  19815. return Material._ClockWiseSideOrientation;
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19821. get: function () {
  19822. return Material._CounterClockWiseSideOrientation;
  19823. },
  19824. enumerable: true,
  19825. configurable: true
  19826. });
  19827. Object.defineProperty(Material.prototype, "wireframe", {
  19828. get: function () {
  19829. return this._fillMode === Material.WireFrameFillMode;
  19830. },
  19831. set: function (value) {
  19832. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19833. },
  19834. enumerable: true,
  19835. configurable: true
  19836. });
  19837. Object.defineProperty(Material.prototype, "pointsCloud", {
  19838. get: function () {
  19839. return this._fillMode === Material.PointFillMode;
  19840. },
  19841. set: function (value) {
  19842. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(Material.prototype, "fillMode", {
  19848. get: function () {
  19849. return this._fillMode;
  19850. },
  19851. set: function (value) {
  19852. this._fillMode = value;
  19853. },
  19854. enumerable: true,
  19855. configurable: true
  19856. });
  19857. Object.defineProperty(Material.prototype, "isFrozen", {
  19858. get: function () {
  19859. return this.checkReadyOnlyOnce;
  19860. },
  19861. enumerable: true,
  19862. configurable: true
  19863. });
  19864. Material.prototype.freeze = function () {
  19865. this.checkReadyOnlyOnce = true;
  19866. };
  19867. Material.prototype.unfreeze = function () {
  19868. this.checkReadyOnlyOnce = false;
  19869. };
  19870. Material.prototype.isReady = function (mesh, useInstances) {
  19871. return true;
  19872. };
  19873. Material.prototype.getEffect = function () {
  19874. return this._effect;
  19875. };
  19876. Material.prototype.getScene = function () {
  19877. return this._scene;
  19878. };
  19879. Material.prototype.needAlphaBlending = function () {
  19880. return (this.alpha < 1.0);
  19881. };
  19882. Material.prototype.needAlphaTesting = function () {
  19883. return false;
  19884. };
  19885. Material.prototype.getAlphaTestTexture = function () {
  19886. return null;
  19887. };
  19888. Material.prototype.trackCreation = function (onCompiled, onError) {
  19889. };
  19890. Material.prototype.markDirty = function () {
  19891. this._wasPreviouslyReady = false;
  19892. };
  19893. Material.prototype._preBind = function () {
  19894. var engine = this._scene.getEngine();
  19895. engine.enableEffect(this._effect);
  19896. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19897. };
  19898. Material.prototype.bind = function (world, mesh) {
  19899. this._scene._cachedMaterial = this;
  19900. if (this.onBind) {
  19901. this.onBind(this, mesh);
  19902. }
  19903. if (this.disableDepthWrite) {
  19904. var engine = this._scene.getEngine();
  19905. this._cachedDepthWriteState = engine.getDepthWrite();
  19906. engine.setDepthWrite(false);
  19907. }
  19908. };
  19909. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19910. };
  19911. Material.prototype.unbind = function () {
  19912. if (this.disableDepthWrite) {
  19913. var engine = this._scene.getEngine();
  19914. engine.setDepthWrite(this._cachedDepthWriteState);
  19915. }
  19916. };
  19917. Material.prototype.clone = function (name) {
  19918. return null;
  19919. };
  19920. Material.prototype.getBindedMeshes = function () {
  19921. var result = new Array();
  19922. for (var index = 0; index < this._scene.meshes.length; index++) {
  19923. var mesh = this._scene.meshes[index];
  19924. if (mesh.material === this) {
  19925. result.push(mesh);
  19926. }
  19927. }
  19928. return result;
  19929. };
  19930. Material.prototype.dispose = function (forceDisposeEffect) {
  19931. // Animations
  19932. this.getScene().stopAnimation(this);
  19933. // Remove from scene
  19934. var index = this._scene.materials.indexOf(this);
  19935. if (index >= 0) {
  19936. this._scene.materials.splice(index, 1);
  19937. }
  19938. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19939. if (forceDisposeEffect && this._effect) {
  19940. this._scene.getEngine()._releaseEffect(this._effect);
  19941. this._effect = null;
  19942. }
  19943. // Remove from meshes
  19944. for (index = 0; index < this._scene.meshes.length; index++) {
  19945. var mesh = this._scene.meshes[index];
  19946. if (mesh.material === this) {
  19947. mesh.material = null;
  19948. }
  19949. }
  19950. // Callback
  19951. if (this.onDispose) {
  19952. this.onDispose();
  19953. }
  19954. };
  19955. Material.prototype.serialize = function () {
  19956. return BABYLON.SerializationHelper.Serialize(this);
  19957. };
  19958. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19959. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19960. multiMaterial.id = parsedMultiMaterial.id;
  19961. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19962. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19963. var subMatId = parsedMultiMaterial.materials[matIndex];
  19964. if (subMatId) {
  19965. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19966. }
  19967. else {
  19968. multiMaterial.subMaterials.push(null);
  19969. }
  19970. }
  19971. return multiMaterial;
  19972. };
  19973. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19974. if (!parsedMaterial.customType) {
  19975. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19976. }
  19977. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19978. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19979. ;
  19980. };
  19981. Material._TriangleFillMode = 0;
  19982. Material._WireFrameFillMode = 1;
  19983. Material._PointFillMode = 2;
  19984. Material._ClockWiseSideOrientation = 0;
  19985. Material._CounterClockWiseSideOrientation = 1;
  19986. __decorate([
  19987. BABYLON.serialize()
  19988. ], Material.prototype, "id", void 0);
  19989. __decorate([
  19990. BABYLON.serialize()
  19991. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  19992. __decorate([
  19993. BABYLON.serialize()
  19994. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  19995. __decorate([
  19996. BABYLON.serialize()
  19997. ], Material.prototype, "state", void 0);
  19998. __decorate([
  19999. BABYLON.serialize()
  20000. ], Material.prototype, "alpha", void 0);
  20001. __decorate([
  20002. BABYLON.serialize()
  20003. ], Material.prototype, "backFaceCulling", void 0);
  20004. __decorate([
  20005. BABYLON.serialize()
  20006. ], Material.prototype, "sideOrientation", void 0);
  20007. __decorate([
  20008. BABYLON.serialize()
  20009. ], Material.prototype, "alphaMode", void 0);
  20010. __decorate([
  20011. BABYLON.serialize()
  20012. ], Material.prototype, "disableDepthWrite", void 0);
  20013. __decorate([
  20014. BABYLON.serialize()
  20015. ], Material.prototype, "fogEnabled", void 0);
  20016. __decorate([
  20017. BABYLON.serialize()
  20018. ], Material.prototype, "pointSize", void 0);
  20019. __decorate([
  20020. BABYLON.serialize()
  20021. ], Material.prototype, "zOffset", void 0);
  20022. __decorate([
  20023. BABYLON.serialize()
  20024. ], Material.prototype, "wireframe", null);
  20025. __decorate([
  20026. BABYLON.serialize()
  20027. ], Material.prototype, "pointsCloud", null);
  20028. __decorate([
  20029. BABYLON.serialize()
  20030. ], Material.prototype, "fillMode", null);
  20031. return Material;
  20032. })();
  20033. BABYLON.Material = Material;
  20034. })(BABYLON || (BABYLON = {}));
  20035. var BABYLON;
  20036. (function (BABYLON) {
  20037. var StandardMaterialDefines = (function (_super) {
  20038. __extends(StandardMaterialDefines, _super);
  20039. function StandardMaterialDefines() {
  20040. _super.call(this);
  20041. this.DIFFUSE = false;
  20042. this.AMBIENT = false;
  20043. this.OPACITY = false;
  20044. this.OPACITYRGB = false;
  20045. this.REFLECTION = false;
  20046. this.EMISSIVE = false;
  20047. this.SPECULAR = false;
  20048. this.BUMP = false;
  20049. this.PARALLAX = false;
  20050. this.PARALLAXOCCLUSION = false;
  20051. this.SPECULAROVERALPHA = false;
  20052. this.CLIPPLANE = false;
  20053. this.ALPHATEST = false;
  20054. this.ALPHAFROMDIFFUSE = false;
  20055. this.POINTSIZE = false;
  20056. this.FOG = false;
  20057. this.LIGHT0 = false;
  20058. this.LIGHT1 = false;
  20059. this.LIGHT2 = false;
  20060. this.LIGHT3 = false;
  20061. this.SPOTLIGHT0 = false;
  20062. this.SPOTLIGHT1 = false;
  20063. this.SPOTLIGHT2 = false;
  20064. this.SPOTLIGHT3 = false;
  20065. this.HEMILIGHT0 = false;
  20066. this.HEMILIGHT1 = false;
  20067. this.HEMILIGHT2 = false;
  20068. this.HEMILIGHT3 = false;
  20069. this.POINTLIGHT0 = false;
  20070. this.POINTLIGHT1 = false;
  20071. this.POINTLIGHT2 = false;
  20072. this.POINTLIGHT3 = false;
  20073. this.DIRLIGHT0 = false;
  20074. this.DIRLIGHT1 = false;
  20075. this.DIRLIGHT2 = false;
  20076. this.DIRLIGHT3 = false;
  20077. this.SPECULARTERM = false;
  20078. this.SHADOW0 = false;
  20079. this.SHADOW1 = false;
  20080. this.SHADOW2 = false;
  20081. this.SHADOW3 = false;
  20082. this.SHADOWS = false;
  20083. this.SHADOWVSM0 = false;
  20084. this.SHADOWVSM1 = false;
  20085. this.SHADOWVSM2 = false;
  20086. this.SHADOWVSM3 = false;
  20087. this.SHADOWPCF0 = false;
  20088. this.SHADOWPCF1 = false;
  20089. this.SHADOWPCF2 = false;
  20090. this.SHADOWPCF3 = false;
  20091. this.DIFFUSEFRESNEL = false;
  20092. this.OPACITYFRESNEL = false;
  20093. this.REFLECTIONFRESNEL = false;
  20094. this.REFRACTIONFRESNEL = false;
  20095. this.EMISSIVEFRESNEL = false;
  20096. this.FRESNEL = false;
  20097. this.NORMAL = false;
  20098. this.UV1 = false;
  20099. this.UV2 = false;
  20100. this.VERTEXCOLOR = false;
  20101. this.VERTEXALPHA = false;
  20102. this.NUM_BONE_INFLUENCERS = 0;
  20103. this.BonesPerMesh = 0;
  20104. this.INSTANCES = false;
  20105. this.GLOSSINESS = false;
  20106. this.ROUGHNESS = false;
  20107. this.EMISSIVEASILLUMINATION = false;
  20108. this.LINKEMISSIVEWITHDIFFUSE = false;
  20109. this.REFLECTIONFRESNELFROMSPECULAR = false;
  20110. this.LIGHTMAP = false;
  20111. this.USELIGHTMAPASSHADOWMAP = false;
  20112. this.REFLECTIONMAP_3D = false;
  20113. this.REFLECTIONMAP_SPHERICAL = false;
  20114. this.REFLECTIONMAP_PLANAR = false;
  20115. this.REFLECTIONMAP_CUBIC = false;
  20116. this.REFLECTIONMAP_PROJECTION = false;
  20117. this.REFLECTIONMAP_SKYBOX = false;
  20118. this.REFLECTIONMAP_EXPLICIT = false;
  20119. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  20120. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  20121. this.INVERTCUBICMAP = false;
  20122. this.LOGARITHMICDEPTH = false;
  20123. this.REFRACTION = false;
  20124. this.REFRACTIONMAP_3D = false;
  20125. this.REFLECTIONOVERALPHA = false;
  20126. this._keys = Object.keys(this);
  20127. }
  20128. return StandardMaterialDefines;
  20129. })(BABYLON.MaterialDefines);
  20130. var StandardMaterial = (function (_super) {
  20131. __extends(StandardMaterial, _super);
  20132. function StandardMaterial(name, scene) {
  20133. var _this = this;
  20134. _super.call(this, name, scene);
  20135. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20136. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  20137. this.specularColor = new BABYLON.Color3(1, 1, 1);
  20138. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  20139. this.specularPower = 64;
  20140. this.useAlphaFromDiffuseTexture = false;
  20141. this.useEmissiveAsIllumination = false;
  20142. this.linkEmissiveWithDiffuse = false;
  20143. this.useReflectionFresnelFromSpecular = false;
  20144. this.useSpecularOverAlpha = false;
  20145. this.useReflectionOverAlpha = false;
  20146. this.disableLighting = false;
  20147. this.useParallax = false;
  20148. this.useParallaxOcclusion = false;
  20149. this.parallaxScaleBias = 0.05;
  20150. this.roughness = 0;
  20151. this.indexOfRefraction = 0.98;
  20152. this.invertRefractionY = true;
  20153. this.useLightmapAsShadowmap = false;
  20154. this.useGlossinessFromSpecularMapAlpha = false;
  20155. this._renderTargets = new BABYLON.SmartArray(16);
  20156. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  20157. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  20158. this._defines = new StandardMaterialDefines();
  20159. this._cachedDefines = new StandardMaterialDefines();
  20160. this._cachedDefines.BonesPerMesh = -1;
  20161. this.getRenderTargetTextures = function () {
  20162. _this._renderTargets.reset();
  20163. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  20164. _this._renderTargets.push(_this.reflectionTexture);
  20165. }
  20166. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  20167. _this._renderTargets.push(_this.refractionTexture);
  20168. }
  20169. return _this._renderTargets;
  20170. };
  20171. }
  20172. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  20173. get: function () {
  20174. return this._useLogarithmicDepth;
  20175. },
  20176. set: function (value) {
  20177. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  20178. },
  20179. enumerable: true,
  20180. configurable: true
  20181. });
  20182. StandardMaterial.prototype.needAlphaBlending = function () {
  20183. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  20184. };
  20185. StandardMaterial.prototype.needAlphaTesting = function () {
  20186. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  20187. };
  20188. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  20189. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  20190. };
  20191. StandardMaterial.prototype.getAlphaTestTexture = function () {
  20192. return this.diffuseTexture;
  20193. };
  20194. // Methods
  20195. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  20196. if (!mesh) {
  20197. return true;
  20198. }
  20199. if (this._defines.INSTANCES !== useInstances) {
  20200. return false;
  20201. }
  20202. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  20203. return true;
  20204. }
  20205. return false;
  20206. };
  20207. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  20208. if (this.isFrozen) {
  20209. if (this._wasPreviouslyReady) {
  20210. return true;
  20211. }
  20212. }
  20213. var scene = this.getScene();
  20214. if (!this.checkReadyOnEveryCall) {
  20215. if (this._renderId === scene.getRenderId()) {
  20216. if (this._checkCache(scene, mesh, useInstances)) {
  20217. return true;
  20218. }
  20219. }
  20220. }
  20221. var engine = scene.getEngine();
  20222. var needNormals = false;
  20223. var needUVs = false;
  20224. this._defines.reset();
  20225. // Textures
  20226. if (scene.texturesEnabled) {
  20227. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20228. if (!this.diffuseTexture.isReady()) {
  20229. return false;
  20230. }
  20231. else {
  20232. needUVs = true;
  20233. this._defines.DIFFUSE = true;
  20234. }
  20235. }
  20236. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20237. if (!this.ambientTexture.isReady()) {
  20238. return false;
  20239. }
  20240. else {
  20241. needUVs = true;
  20242. this._defines.AMBIENT = true;
  20243. }
  20244. }
  20245. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20246. if (!this.opacityTexture.isReady()) {
  20247. return false;
  20248. }
  20249. else {
  20250. needUVs = true;
  20251. this._defines.OPACITY = true;
  20252. if (this.opacityTexture.getAlphaFromRGB) {
  20253. this._defines.OPACITYRGB = true;
  20254. }
  20255. }
  20256. }
  20257. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20258. if (!this.reflectionTexture.isReady()) {
  20259. return false;
  20260. }
  20261. else {
  20262. needNormals = true;
  20263. this._defines.REFLECTION = true;
  20264. if (this.roughness > 0) {
  20265. this._defines.ROUGHNESS = true;
  20266. }
  20267. if (this.useReflectionOverAlpha) {
  20268. this._defines.REFLECTIONOVERALPHA = true;
  20269. }
  20270. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  20271. this._defines.INVERTCUBICMAP = true;
  20272. }
  20273. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  20274. switch (this.reflectionTexture.coordinatesMode) {
  20275. case BABYLON.Texture.CUBIC_MODE:
  20276. case BABYLON.Texture.INVCUBIC_MODE:
  20277. this._defines.REFLECTIONMAP_CUBIC = true;
  20278. break;
  20279. case BABYLON.Texture.EXPLICIT_MODE:
  20280. this._defines.REFLECTIONMAP_EXPLICIT = true;
  20281. break;
  20282. case BABYLON.Texture.PLANAR_MODE:
  20283. this._defines.REFLECTIONMAP_PLANAR = true;
  20284. break;
  20285. case BABYLON.Texture.PROJECTION_MODE:
  20286. this._defines.REFLECTIONMAP_PROJECTION = true;
  20287. break;
  20288. case BABYLON.Texture.SKYBOX_MODE:
  20289. this._defines.REFLECTIONMAP_SKYBOX = true;
  20290. break;
  20291. case BABYLON.Texture.SPHERICAL_MODE:
  20292. this._defines.REFLECTIONMAP_SPHERICAL = true;
  20293. break;
  20294. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  20295. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  20296. break;
  20297. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  20298. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  20299. break;
  20300. }
  20301. }
  20302. }
  20303. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20304. if (!this.emissiveTexture.isReady()) {
  20305. return false;
  20306. }
  20307. else {
  20308. needUVs = true;
  20309. this._defines.EMISSIVE = true;
  20310. }
  20311. }
  20312. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20313. if (!this.lightmapTexture.isReady()) {
  20314. return false;
  20315. }
  20316. else {
  20317. needUVs = true;
  20318. this._defines.LIGHTMAP = true;
  20319. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  20320. }
  20321. }
  20322. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20323. if (!this.specularTexture.isReady()) {
  20324. return false;
  20325. }
  20326. else {
  20327. needUVs = true;
  20328. this._defines.SPECULAR = true;
  20329. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  20330. }
  20331. }
  20332. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  20333. if (!this.bumpTexture.isReady()) {
  20334. return false;
  20335. }
  20336. else {
  20337. needUVs = true;
  20338. this._defines.BUMP = true;
  20339. if (this.useParallax) {
  20340. this._defines.PARALLAX = true;
  20341. if (this.useParallaxOcclusion) {
  20342. this._defines.PARALLAXOCCLUSION = true;
  20343. }
  20344. }
  20345. }
  20346. }
  20347. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20348. if (!this.refractionTexture.isReady()) {
  20349. return false;
  20350. }
  20351. else {
  20352. needUVs = true;
  20353. this._defines.REFRACTION = true;
  20354. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  20355. }
  20356. }
  20357. }
  20358. // Effect
  20359. if (scene.clipPlane) {
  20360. this._defines.CLIPPLANE = true;
  20361. }
  20362. if (engine.getAlphaTesting()) {
  20363. this._defines.ALPHATEST = true;
  20364. }
  20365. if (this._shouldUseAlphaFromDiffuseTexture()) {
  20366. this._defines.ALPHAFROMDIFFUSE = true;
  20367. }
  20368. if (this.useEmissiveAsIllumination) {
  20369. this._defines.EMISSIVEASILLUMINATION = true;
  20370. }
  20371. if (this.linkEmissiveWithDiffuse) {
  20372. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  20373. }
  20374. if (this.useLogarithmicDepth) {
  20375. this._defines.LOGARITHMICDEPTH = true;
  20376. }
  20377. // Point size
  20378. if (this.pointsCloud || scene.forcePointsCloud) {
  20379. this._defines.POINTSIZE = true;
  20380. }
  20381. // Fog
  20382. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20383. this._defines.FOG = true;
  20384. }
  20385. if (scene.lightsEnabled && !this.disableLighting) {
  20386. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  20387. }
  20388. if (StandardMaterial.FresnelEnabled) {
  20389. // Fresnel
  20390. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  20391. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  20392. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  20393. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  20394. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20395. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20396. this._defines.DIFFUSEFRESNEL = true;
  20397. }
  20398. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20399. this._defines.OPACITYFRESNEL = true;
  20400. }
  20401. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20402. this._defines.REFLECTIONFRESNEL = true;
  20403. if (this.useReflectionFresnelFromSpecular) {
  20404. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  20405. }
  20406. }
  20407. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20408. this._defines.REFRACTIONFRESNEL = true;
  20409. }
  20410. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20411. this._defines.EMISSIVEFRESNEL = true;
  20412. }
  20413. needNormals = true;
  20414. this._defines.FRESNEL = true;
  20415. }
  20416. }
  20417. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  20418. this._defines.SPECULAROVERALPHA = true;
  20419. }
  20420. // Attribs
  20421. if (mesh) {
  20422. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20423. this._defines.NORMAL = true;
  20424. }
  20425. if (needUVs) {
  20426. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20427. this._defines.UV1 = true;
  20428. }
  20429. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20430. this._defines.UV2 = true;
  20431. }
  20432. }
  20433. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20434. this._defines.VERTEXCOLOR = true;
  20435. if (mesh.hasVertexAlpha) {
  20436. this._defines.VERTEXALPHA = true;
  20437. }
  20438. }
  20439. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  20440. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  20441. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  20442. }
  20443. // Instances
  20444. if (useInstances) {
  20445. this._defines.INSTANCES = true;
  20446. }
  20447. }
  20448. // Get correct effect
  20449. if (!this._defines.isEqual(this._cachedDefines)) {
  20450. this._defines.cloneTo(this._cachedDefines);
  20451. scene.resetCachedMaterial();
  20452. // Fallbacks
  20453. var fallbacks = new BABYLON.EffectFallbacks();
  20454. if (this._defines.REFLECTION) {
  20455. fallbacks.addFallback(0, "REFLECTION");
  20456. }
  20457. if (this._defines.SPECULAR) {
  20458. fallbacks.addFallback(0, "SPECULAR");
  20459. }
  20460. if (this._defines.BUMP) {
  20461. fallbacks.addFallback(0, "BUMP");
  20462. }
  20463. if (this._defines.PARALLAX) {
  20464. fallbacks.addFallback(1, "PARALLAX");
  20465. }
  20466. if (this._defines.PARALLAXOCCLUSION) {
  20467. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  20468. }
  20469. if (this._defines.SPECULAROVERALPHA) {
  20470. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20471. }
  20472. if (this._defines.FOG) {
  20473. fallbacks.addFallback(1, "FOG");
  20474. }
  20475. if (this._defines.POINTSIZE) {
  20476. fallbacks.addFallback(0, "POINTSIZE");
  20477. }
  20478. if (this._defines.LOGARITHMICDEPTH) {
  20479. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20480. }
  20481. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  20482. if (this._defines.SPECULARTERM) {
  20483. fallbacks.addFallback(0, "SPECULARTERM");
  20484. }
  20485. if (this._defines.DIFFUSEFRESNEL) {
  20486. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20487. }
  20488. if (this._defines.OPACITYFRESNEL) {
  20489. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20490. }
  20491. if (this._defines.REFLECTIONFRESNEL) {
  20492. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20493. }
  20494. if (this._defines.EMISSIVEFRESNEL) {
  20495. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20496. }
  20497. if (this._defines.FRESNEL) {
  20498. fallbacks.addFallback(4, "FRESNEL");
  20499. }
  20500. //Attributes
  20501. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20502. if (this._defines.NORMAL) {
  20503. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20504. }
  20505. if (this._defines.UV1) {
  20506. attribs.push(BABYLON.VertexBuffer.UVKind);
  20507. }
  20508. if (this._defines.UV2) {
  20509. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20510. }
  20511. if (this._defines.VERTEXCOLOR) {
  20512. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20513. }
  20514. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20515. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  20516. // Legacy browser patch
  20517. var shaderName = "default";
  20518. if (!scene.getEngine().getCaps().standardDerivatives) {
  20519. shaderName = "legacydefault";
  20520. }
  20521. var join = this._defines.toString();
  20522. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20523. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20524. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20525. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20526. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20527. "vFogInfos", "vFogColor", "pointSize",
  20528. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20529. "mBones",
  20530. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20531. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20532. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20533. "logarithmicDepthConstant"
  20534. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20535. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20536. ], join, fallbacks, this.onCompiled, this.onError);
  20537. }
  20538. if (!this._effect.isReady()) {
  20539. return false;
  20540. }
  20541. this._renderId = scene.getRenderId();
  20542. this._wasPreviouslyReady = true;
  20543. if (mesh) {
  20544. if (!mesh._materialDefines) {
  20545. mesh._materialDefines = new StandardMaterialDefines();
  20546. }
  20547. this._defines.cloneTo(mesh._materialDefines);
  20548. }
  20549. return true;
  20550. };
  20551. StandardMaterial.prototype.unbind = function () {
  20552. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20553. this._effect.setTexture("reflection2DSampler", null);
  20554. }
  20555. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20556. this._effect.setTexture("refraction2DSampler", null);
  20557. }
  20558. _super.prototype.unbind.call(this);
  20559. };
  20560. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20561. this._effect.setMatrix("world", world);
  20562. };
  20563. StandardMaterial.prototype.bind = function (world, mesh) {
  20564. var scene = this.getScene();
  20565. // Matrices
  20566. this.bindOnlyWorldMatrix(world);
  20567. // Bones
  20568. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  20569. if (scene.getCachedMaterial() !== this) {
  20570. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20571. if (StandardMaterial.FresnelEnabled) {
  20572. // Fresnel
  20573. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20574. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20575. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20576. }
  20577. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20578. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20579. }
  20580. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20581. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20582. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20583. }
  20584. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20585. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20586. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20587. }
  20588. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20589. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20590. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20591. }
  20592. }
  20593. // Textures
  20594. if (scene.texturesEnabled) {
  20595. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20596. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20597. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20598. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20599. }
  20600. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20601. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20602. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20603. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20604. }
  20605. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20606. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20607. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20608. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20609. }
  20610. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20611. if (this.reflectionTexture.isCube) {
  20612. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20613. }
  20614. else {
  20615. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20616. }
  20617. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20618. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20619. }
  20620. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20621. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20622. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20623. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20624. }
  20625. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20626. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20627. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20628. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20629. }
  20630. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20631. this._effect.setTexture("specularSampler", this.specularTexture);
  20632. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20633. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20634. }
  20635. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20636. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20637. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  20638. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20639. }
  20640. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20641. var depth = 1.0;
  20642. if (this.refractionTexture.isCube) {
  20643. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20644. }
  20645. else {
  20646. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20647. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20648. if (this.refractionTexture.depth) {
  20649. depth = this.refractionTexture.depth;
  20650. }
  20651. }
  20652. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20653. }
  20654. }
  20655. // Clip plane
  20656. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  20657. // Point size
  20658. if (this.pointsCloud) {
  20659. this._effect.setFloat("pointSize", this.pointSize);
  20660. }
  20661. // Colors
  20662. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20663. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20664. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20665. if (this._defines.SPECULARTERM) {
  20666. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20667. }
  20668. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20669. }
  20670. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20671. // Diffuse
  20672. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20673. // Lights
  20674. if (scene.lightsEnabled && !this.disableLighting) {
  20675. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  20676. }
  20677. // View
  20678. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20679. this._effect.setMatrix("view", scene.getViewMatrix());
  20680. }
  20681. // Fog
  20682. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  20683. // Log. depth
  20684. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  20685. }
  20686. _super.prototype.bind.call(this, world, mesh);
  20687. };
  20688. StandardMaterial.prototype.getAnimatables = function () {
  20689. var results = [];
  20690. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20691. results.push(this.diffuseTexture);
  20692. }
  20693. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20694. results.push(this.ambientTexture);
  20695. }
  20696. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20697. results.push(this.opacityTexture);
  20698. }
  20699. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20700. results.push(this.reflectionTexture);
  20701. }
  20702. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20703. results.push(this.emissiveTexture);
  20704. }
  20705. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20706. results.push(this.specularTexture);
  20707. }
  20708. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20709. results.push(this.bumpTexture);
  20710. }
  20711. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20712. results.push(this.lightmapTexture);
  20713. }
  20714. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20715. results.push(this.refractionTexture);
  20716. }
  20717. return results;
  20718. };
  20719. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20720. if (this.diffuseTexture) {
  20721. this.diffuseTexture.dispose();
  20722. }
  20723. if (this.ambientTexture) {
  20724. this.ambientTexture.dispose();
  20725. }
  20726. if (this.opacityTexture) {
  20727. this.opacityTexture.dispose();
  20728. }
  20729. if (this.reflectionTexture) {
  20730. this.reflectionTexture.dispose();
  20731. }
  20732. if (this.emissiveTexture) {
  20733. this.emissiveTexture.dispose();
  20734. }
  20735. if (this.specularTexture) {
  20736. this.specularTexture.dispose();
  20737. }
  20738. if (this.bumpTexture) {
  20739. this.bumpTexture.dispose();
  20740. }
  20741. if (this.lightmapTexture) {
  20742. this.lightmapTexture.dispose();
  20743. }
  20744. if (this.refractionTexture) {
  20745. this.refractionTexture.dispose();
  20746. }
  20747. _super.prototype.dispose.call(this, forceDisposeEffect);
  20748. };
  20749. StandardMaterial.prototype.clone = function (name) {
  20750. var _this = this;
  20751. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  20752. };
  20753. StandardMaterial.prototype.serialize = function () {
  20754. return BABYLON.SerializationHelper.Serialize(this);
  20755. };
  20756. // Statics
  20757. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20758. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  20759. };
  20760. // Flags used to enable or disable a type of texture for all Standard Materials
  20761. StandardMaterial.DiffuseTextureEnabled = true;
  20762. StandardMaterial.AmbientTextureEnabled = true;
  20763. StandardMaterial.OpacityTextureEnabled = true;
  20764. StandardMaterial.ReflectionTextureEnabled = true;
  20765. StandardMaterial.EmissiveTextureEnabled = true;
  20766. StandardMaterial.SpecularTextureEnabled = true;
  20767. StandardMaterial.BumpTextureEnabled = true;
  20768. StandardMaterial.FresnelEnabled = true;
  20769. StandardMaterial.LightmapTextureEnabled = true;
  20770. StandardMaterial.RefractionTextureEnabled = true;
  20771. __decorate([
  20772. BABYLON.serializeAsTexture()
  20773. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  20774. __decorate([
  20775. BABYLON.serializeAsTexture()
  20776. ], StandardMaterial.prototype, "ambientTexture", void 0);
  20777. __decorate([
  20778. BABYLON.serializeAsTexture()
  20779. ], StandardMaterial.prototype, "opacityTexture", void 0);
  20780. __decorate([
  20781. BABYLON.serializeAsTexture()
  20782. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  20783. __decorate([
  20784. BABYLON.serializeAsTexture()
  20785. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  20786. __decorate([
  20787. BABYLON.serializeAsTexture()
  20788. ], StandardMaterial.prototype, "specularTexture", void 0);
  20789. __decorate([
  20790. BABYLON.serializeAsTexture()
  20791. ], StandardMaterial.prototype, "bumpTexture", void 0);
  20792. __decorate([
  20793. BABYLON.serializeAsTexture()
  20794. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  20795. __decorate([
  20796. BABYLON.serializeAsTexture()
  20797. ], StandardMaterial.prototype, "refractionTexture", void 0);
  20798. __decorate([
  20799. BABYLON.serializeAsColor3("ambient")
  20800. ], StandardMaterial.prototype, "ambientColor", void 0);
  20801. __decorate([
  20802. BABYLON.serializeAsColor3("diffuse")
  20803. ], StandardMaterial.prototype, "diffuseColor", void 0);
  20804. __decorate([
  20805. BABYLON.serializeAsColor3("specular")
  20806. ], StandardMaterial.prototype, "specularColor", void 0);
  20807. __decorate([
  20808. BABYLON.serializeAsColor3("emissive")
  20809. ], StandardMaterial.prototype, "emissiveColor", void 0);
  20810. __decorate([
  20811. BABYLON.serialize()
  20812. ], StandardMaterial.prototype, "specularPower", void 0);
  20813. __decorate([
  20814. BABYLON.serialize()
  20815. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  20816. __decorate([
  20817. BABYLON.serialize()
  20818. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  20819. __decorate([
  20820. BABYLON.serialize()
  20821. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  20822. __decorate([
  20823. BABYLON.serialize()
  20824. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  20825. __decorate([
  20826. BABYLON.serialize()
  20827. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  20828. __decorate([
  20829. BABYLON.serialize()
  20830. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  20831. __decorate([
  20832. BABYLON.serialize()
  20833. ], StandardMaterial.prototype, "disableLighting", void 0);
  20834. __decorate([
  20835. BABYLON.serialize()
  20836. ], StandardMaterial.prototype, "useParallax", void 0);
  20837. __decorate([
  20838. BABYLON.serialize()
  20839. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  20840. __decorate([
  20841. BABYLON.serialize()
  20842. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  20843. __decorate([
  20844. BABYLON.serialize()
  20845. ], StandardMaterial.prototype, "roughness", void 0);
  20846. __decorate([
  20847. BABYLON.serialize()
  20848. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  20849. __decorate([
  20850. BABYLON.serialize()
  20851. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  20852. __decorate([
  20853. BABYLON.serialize()
  20854. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  20855. __decorate([
  20856. BABYLON.serializeAsFresnelParameters()
  20857. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  20858. __decorate([
  20859. BABYLON.serializeAsFresnelParameters()
  20860. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  20861. __decorate([
  20862. BABYLON.serializeAsFresnelParameters()
  20863. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  20864. __decorate([
  20865. BABYLON.serializeAsFresnelParameters()
  20866. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  20867. __decorate([
  20868. BABYLON.serializeAsFresnelParameters()
  20869. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  20870. __decorate([
  20871. BABYLON.serialize()
  20872. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  20873. __decorate([
  20874. BABYLON.serialize()
  20875. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  20876. return StandardMaterial;
  20877. })(BABYLON.Material);
  20878. BABYLON.StandardMaterial = StandardMaterial;
  20879. })(BABYLON || (BABYLON = {}));
  20880. var BABYLON;
  20881. (function (BABYLON) {
  20882. var MultiMaterial = (function (_super) {
  20883. __extends(MultiMaterial, _super);
  20884. function MultiMaterial(name, scene) {
  20885. _super.call(this, name, scene, true);
  20886. this.subMaterials = new Array();
  20887. scene.multiMaterials.push(this);
  20888. }
  20889. // Properties
  20890. MultiMaterial.prototype.getSubMaterial = function (index) {
  20891. if (index < 0 || index >= this.subMaterials.length) {
  20892. return this.getScene().defaultMaterial;
  20893. }
  20894. return this.subMaterials[index];
  20895. };
  20896. // Methods
  20897. MultiMaterial.prototype.isReady = function (mesh) {
  20898. for (var index = 0; index < this.subMaterials.length; index++) {
  20899. var subMaterial = this.subMaterials[index];
  20900. if (subMaterial) {
  20901. if (!this.subMaterials[index].isReady(mesh)) {
  20902. return false;
  20903. }
  20904. }
  20905. }
  20906. return true;
  20907. };
  20908. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20909. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20910. for (var index = 0; index < this.subMaterials.length; index++) {
  20911. var subMaterial = null;
  20912. if (cloneChildren) {
  20913. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20914. }
  20915. else {
  20916. subMaterial = this.subMaterials[index];
  20917. }
  20918. newMultiMaterial.subMaterials.push(subMaterial);
  20919. }
  20920. return newMultiMaterial;
  20921. };
  20922. MultiMaterial.prototype.serialize = function () {
  20923. var serializationObject = {};
  20924. serializationObject.name = this.name;
  20925. serializationObject.id = this.id;
  20926. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20927. serializationObject.materials = [];
  20928. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20929. var subMat = this.subMaterials[matIndex];
  20930. if (subMat) {
  20931. serializationObject.materials.push(subMat.id);
  20932. }
  20933. else {
  20934. serializationObject.materials.push(null);
  20935. }
  20936. }
  20937. return serializationObject;
  20938. };
  20939. return MultiMaterial;
  20940. })(BABYLON.Material);
  20941. BABYLON.MultiMaterial = MultiMaterial;
  20942. })(BABYLON || (BABYLON = {}));
  20943. var BABYLON;
  20944. (function (BABYLON) {
  20945. var SceneLoader = (function () {
  20946. function SceneLoader() {
  20947. }
  20948. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20949. get: function () {
  20950. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20951. },
  20952. set: function (value) {
  20953. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20954. },
  20955. enumerable: true,
  20956. configurable: true
  20957. });
  20958. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20959. get: function () {
  20960. return SceneLoader._ShowLoadingScreen;
  20961. },
  20962. set: function (value) {
  20963. SceneLoader._ShowLoadingScreen = value;
  20964. },
  20965. enumerable: true,
  20966. configurable: true
  20967. });
  20968. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20969. var dotPosition = sceneFilename.lastIndexOf(".");
  20970. var queryStringPosition = sceneFilename.indexOf("?");
  20971. if (queryStringPosition === -1) {
  20972. queryStringPosition = sceneFilename.length;
  20973. }
  20974. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20975. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20976. var plugin = this._registeredPlugins[index];
  20977. if (plugin.extensions.indexOf(extension) !== -1) {
  20978. return plugin;
  20979. }
  20980. }
  20981. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20982. };
  20983. // Public functions
  20984. SceneLoader.GetPluginForExtension = function (extension) {
  20985. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20986. var plugin = this._registeredPlugins[index];
  20987. if (plugin.extensions.indexOf(extension) !== -1) {
  20988. return plugin;
  20989. }
  20990. }
  20991. return null;
  20992. };
  20993. SceneLoader.RegisterPlugin = function (plugin) {
  20994. plugin.extensions = plugin.extensions.toLowerCase();
  20995. SceneLoader._registeredPlugins.push(plugin);
  20996. };
  20997. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20998. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20999. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  21000. return;
  21001. }
  21002. var loadingToken = {};
  21003. scene._addPendingData(loadingToken);
  21004. var manifestChecked = function (success) {
  21005. scene.database = database;
  21006. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  21007. var importMeshFromData = function (data) {
  21008. var meshes = [];
  21009. var particleSystems = [];
  21010. var skeletons = [];
  21011. try {
  21012. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  21013. if (onerror) {
  21014. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  21015. }
  21016. scene._removePendingData(loadingToken);
  21017. return;
  21018. }
  21019. }
  21020. catch (e) {
  21021. if (onerror) {
  21022. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  21023. }
  21024. scene._removePendingData(loadingToken);
  21025. return;
  21026. }
  21027. if (onsuccess) {
  21028. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  21029. onsuccess(meshes, particleSystems, skeletons);
  21030. scene._removePendingData(loadingToken);
  21031. }
  21032. };
  21033. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21034. // Direct load
  21035. importMeshFromData(sceneFilename.substr(5));
  21036. return;
  21037. }
  21038. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  21039. importMeshFromData(data);
  21040. }, progressCallBack, database);
  21041. };
  21042. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  21043. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21044. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21045. }
  21046. else {
  21047. // If the scene is a data stream or offline support is not enabled, it's a direct load
  21048. manifestChecked(true);
  21049. }
  21050. };
  21051. /**
  21052. * Load a scene
  21053. * @param rootUrl a string that defines the root url for scene and resources
  21054. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21055. * @param engine is the instance of BABYLON.Engine to use to create the scene
  21056. */
  21057. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  21058. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  21059. };
  21060. /**
  21061. * Append a scene
  21062. * @param rootUrl a string that defines the root url for scene and resources
  21063. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21064. * @param scene is the instance of BABYLON.Scene to append to
  21065. */
  21066. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  21067. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  21068. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  21069. return;
  21070. }
  21071. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  21072. var database;
  21073. var loadingToken = {};
  21074. scene._addPendingData(loadingToken);
  21075. if (SceneLoader.ShowLoadingScreen) {
  21076. scene.getEngine().displayLoadingUI();
  21077. }
  21078. var loadSceneFromData = function (data) {
  21079. scene.database = database;
  21080. if (!plugin.load(scene, data, rootUrl)) {
  21081. if (onerror) {
  21082. onerror(scene);
  21083. }
  21084. scene._removePendingData(loadingToken);
  21085. scene.getEngine().hideLoadingUI();
  21086. return;
  21087. }
  21088. if (onsuccess) {
  21089. onsuccess(scene);
  21090. }
  21091. scene._removePendingData(loadingToken);
  21092. if (SceneLoader.ShowLoadingScreen) {
  21093. scene.executeWhenReady(function () {
  21094. scene.getEngine().hideLoadingUI();
  21095. });
  21096. }
  21097. };
  21098. var manifestChecked = function (success) {
  21099. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  21100. };
  21101. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21102. // Direct load
  21103. loadSceneFromData(sceneFilename.substr(5));
  21104. return;
  21105. }
  21106. if (rootUrl.indexOf("file:") === -1) {
  21107. if (scene.getEngine().enableOfflineSupport) {
  21108. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21109. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21110. }
  21111. else {
  21112. manifestChecked(true);
  21113. }
  21114. }
  21115. else {
  21116. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  21117. }
  21118. };
  21119. // Flags
  21120. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  21121. SceneLoader._ShowLoadingScreen = true;
  21122. // Members
  21123. SceneLoader._registeredPlugins = new Array();
  21124. return SceneLoader;
  21125. })();
  21126. BABYLON.SceneLoader = SceneLoader;
  21127. ;
  21128. })(BABYLON || (BABYLON = {}));
  21129. var BABYLON;
  21130. (function (BABYLON) {
  21131. var Internals;
  21132. (function (Internals) {
  21133. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  21134. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21135. var parsedMaterial = parsedData.materials[index];
  21136. if (parsedMaterial.id === id) {
  21137. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21138. }
  21139. }
  21140. return null;
  21141. };
  21142. var isDescendantOf = function (mesh, names, hierarchyIds) {
  21143. names = (names instanceof Array) ? names : [names];
  21144. for (var i in names) {
  21145. if (mesh.name === names[i]) {
  21146. hierarchyIds.push(mesh.id);
  21147. return true;
  21148. }
  21149. }
  21150. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  21151. hierarchyIds.push(mesh.id);
  21152. return true;
  21153. }
  21154. return false;
  21155. };
  21156. BABYLON.SceneLoader.RegisterPlugin({
  21157. extensions: ".babylon",
  21158. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21159. var parsedData = JSON.parse(data);
  21160. var loadedSkeletonsIds = [];
  21161. var loadedMaterialsIds = [];
  21162. var hierarchyIds = [];
  21163. var index;
  21164. var cache;
  21165. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21166. var parsedMesh = parsedData.meshes[index];
  21167. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21168. if (meshesNames instanceof Array) {
  21169. // Remove found mesh name from list.
  21170. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21171. }
  21172. //Geometry?
  21173. if (parsedMesh.geometryId) {
  21174. //does the file contain geometries?
  21175. if (parsedData.geometries) {
  21176. //find the correct geometry and add it to the scene
  21177. var found = false;
  21178. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21179. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21180. return;
  21181. }
  21182. else {
  21183. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21184. if (parsedGeometryData.id === parsedMesh.geometryId) {
  21185. switch (geometryType) {
  21186. case "boxes":
  21187. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  21188. break;
  21189. case "spheres":
  21190. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  21191. break;
  21192. case "cylinders":
  21193. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  21194. break;
  21195. case "toruses":
  21196. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  21197. break;
  21198. case "grounds":
  21199. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  21200. break;
  21201. case "planes":
  21202. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  21203. break;
  21204. case "torusKnots":
  21205. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  21206. break;
  21207. case "vertexData":
  21208. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  21209. break;
  21210. }
  21211. found = true;
  21212. }
  21213. });
  21214. }
  21215. });
  21216. if (!found) {
  21217. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21218. }
  21219. }
  21220. }
  21221. // Material ?
  21222. if (parsedMesh.materialId) {
  21223. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21224. if (!materialFound && parsedData.multiMaterials) {
  21225. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  21226. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21227. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  21228. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  21229. var subMatId = parsedMultiMaterial.materials[matIndex];
  21230. loadedMaterialsIds.push(subMatId);
  21231. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21232. }
  21233. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21234. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21235. materialFound = true;
  21236. break;
  21237. }
  21238. }
  21239. }
  21240. if (!materialFound) {
  21241. loadedMaterialsIds.push(parsedMesh.materialId);
  21242. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21243. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21244. }
  21245. }
  21246. }
  21247. // Skeleton ?
  21248. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21249. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21250. if (!skeletonAlreadyLoaded) {
  21251. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  21252. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21253. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21254. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  21255. loadedSkeletonsIds.push(parsedSkeleton.id);
  21256. }
  21257. }
  21258. }
  21259. }
  21260. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21261. meshes.push(mesh);
  21262. }
  21263. }
  21264. // Connecting parents
  21265. var currentMesh;
  21266. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21267. currentMesh = scene.meshes[index];
  21268. if (currentMesh._waitingParentId) {
  21269. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21270. currentMesh._waitingParentId = undefined;
  21271. }
  21272. }
  21273. // freeze and compute world matrix application
  21274. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21275. currentMesh = scene.meshes[index];
  21276. if (currentMesh._waitingFreezeWorldMatrix) {
  21277. currentMesh.freezeWorldMatrix();
  21278. currentMesh._waitingFreezeWorldMatrix = undefined;
  21279. }
  21280. else {
  21281. currentMesh.computeWorldMatrix(true);
  21282. }
  21283. }
  21284. // Particles
  21285. if (parsedData.particleSystems) {
  21286. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21287. var parsedParticleSystem = parsedData.particleSystems[index];
  21288. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21289. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  21290. }
  21291. }
  21292. }
  21293. return true;
  21294. },
  21295. load: function (scene, data, rootUrl) {
  21296. var parsedData = JSON.parse(data);
  21297. // Scene
  21298. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21299. scene.autoClear = parsedData.autoClear;
  21300. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21301. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21302. if (parsedData.gravity) {
  21303. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21304. }
  21305. // Fog
  21306. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21307. scene.fogMode = parsedData.fogMode;
  21308. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21309. scene.fogStart = parsedData.fogStart;
  21310. scene.fogEnd = parsedData.fogEnd;
  21311. scene.fogDensity = parsedData.fogDensity;
  21312. }
  21313. //Physics
  21314. if (parsedData.physicsEnabled) {
  21315. var physicsPlugin;
  21316. if (parsedData.physicsEngine === "cannon") {
  21317. physicsPlugin = new BABYLON.CannonJSPlugin();
  21318. }
  21319. else if (parsedData.physicsEngine === "oimo") {
  21320. physicsPlugin = new BABYLON.OimoJSPlugin();
  21321. }
  21322. //else - default engine, which is currently oimo
  21323. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  21324. scene.enablePhysics(physicsGravity, physicsPlugin);
  21325. }
  21326. //collisions, if defined. otherwise, default is true
  21327. if (parsedData.collisionsEnabled != undefined) {
  21328. scene.collisionsEnabled = parsedData.collisionsEnabled;
  21329. }
  21330. scene.workerCollisions = !!parsedData.workerCollisions;
  21331. var index;
  21332. var cache;
  21333. // Lights
  21334. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  21335. var parsedLight = parsedData.lights[index];
  21336. BABYLON.Light.Parse(parsedLight, scene);
  21337. }
  21338. // Animations
  21339. if (parsedData.animations) {
  21340. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  21341. var parsedAnimation = parsedData.animations[index];
  21342. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21343. }
  21344. }
  21345. // Materials
  21346. if (parsedData.materials) {
  21347. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21348. var parsedMaterial = parsedData.materials[index];
  21349. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21350. }
  21351. }
  21352. if (parsedData.multiMaterials) {
  21353. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  21354. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21355. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21356. }
  21357. }
  21358. // Skeletons
  21359. if (parsedData.skeletons) {
  21360. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21361. var parsedSkeleton = parsedData.skeletons[index];
  21362. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21363. }
  21364. }
  21365. // Geometries
  21366. var geometries = parsedData.geometries;
  21367. if (geometries) {
  21368. // Boxes
  21369. var boxes = geometries.boxes;
  21370. if (boxes) {
  21371. for (index = 0, cache = boxes.length; index < cache; index++) {
  21372. var parsedBox = boxes[index];
  21373. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21374. }
  21375. }
  21376. // Spheres
  21377. var spheres = geometries.spheres;
  21378. if (spheres) {
  21379. for (index = 0, cache = spheres.length; index < cache; index++) {
  21380. var parsedSphere = spheres[index];
  21381. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21382. }
  21383. }
  21384. // Cylinders
  21385. var cylinders = geometries.cylinders;
  21386. if (cylinders) {
  21387. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21388. var parsedCylinder = cylinders[index];
  21389. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21390. }
  21391. }
  21392. // Toruses
  21393. var toruses = geometries.toruses;
  21394. if (toruses) {
  21395. for (index = 0, cache = toruses.length; index < cache; index++) {
  21396. var parsedTorus = toruses[index];
  21397. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21398. }
  21399. }
  21400. // Grounds
  21401. var grounds = geometries.grounds;
  21402. if (grounds) {
  21403. for (index = 0, cache = grounds.length; index < cache; index++) {
  21404. var parsedGround = grounds[index];
  21405. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21406. }
  21407. }
  21408. // Planes
  21409. var planes = geometries.planes;
  21410. if (planes) {
  21411. for (index = 0, cache = planes.length; index < cache; index++) {
  21412. var parsedPlane = planes[index];
  21413. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21414. }
  21415. }
  21416. // TorusKnots
  21417. var torusKnots = geometries.torusKnots;
  21418. if (torusKnots) {
  21419. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21420. var parsedTorusKnot = torusKnots[index];
  21421. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21422. }
  21423. }
  21424. // VertexData
  21425. var vertexData = geometries.vertexData;
  21426. if (vertexData) {
  21427. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21428. var parsedVertexData = vertexData[index];
  21429. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21430. }
  21431. }
  21432. }
  21433. // Meshes
  21434. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21435. var parsedMesh = parsedData.meshes[index];
  21436. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21437. }
  21438. // Cameras
  21439. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21440. var parsedCamera = parsedData.cameras[index];
  21441. BABYLON.Camera.Parse(parsedCamera, scene);
  21442. }
  21443. if (parsedData.activeCameraID) {
  21444. scene.setActiveCameraByID(parsedData.activeCameraID);
  21445. }
  21446. // Browsing all the graph to connect the dots
  21447. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21448. var camera = scene.cameras[index];
  21449. if (camera._waitingParentId) {
  21450. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21451. camera._waitingParentId = undefined;
  21452. }
  21453. }
  21454. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21455. var light = scene.lights[index];
  21456. if (light._waitingParentId) {
  21457. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21458. light._waitingParentId = undefined;
  21459. }
  21460. }
  21461. // Sounds
  21462. var loadedSounds = [];
  21463. var loadedSound;
  21464. if (BABYLON.AudioEngine && parsedData.sounds) {
  21465. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21466. var parsedSound = parsedData.sounds[index];
  21467. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21468. if (!parsedSound.url)
  21469. parsedSound.url = parsedSound.name;
  21470. if (!loadedSounds[parsedSound.url]) {
  21471. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21472. loadedSounds[parsedSound.url] = loadedSound;
  21473. }
  21474. else {
  21475. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21476. }
  21477. }
  21478. else {
  21479. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21480. }
  21481. }
  21482. }
  21483. loadedSounds = [];
  21484. // Connect parents & children and parse actions
  21485. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21486. var mesh = scene.meshes[index];
  21487. if (mesh._waitingParentId) {
  21488. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21489. mesh._waitingParentId = undefined;
  21490. }
  21491. if (mesh._waitingActions) {
  21492. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21493. mesh._waitingActions = undefined;
  21494. }
  21495. }
  21496. // freeze world matrix application
  21497. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21498. var currentMesh = scene.meshes[index];
  21499. if (currentMesh._waitingFreezeWorldMatrix) {
  21500. currentMesh.freezeWorldMatrix();
  21501. currentMesh._waitingFreezeWorldMatrix = undefined;
  21502. }
  21503. else {
  21504. currentMesh.computeWorldMatrix(true);
  21505. }
  21506. }
  21507. // Particles Systems
  21508. if (parsedData.particleSystems) {
  21509. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21510. var parsedParticleSystem = parsedData.particleSystems[index];
  21511. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21512. }
  21513. }
  21514. // Lens flares
  21515. if (parsedData.lensFlareSystems) {
  21516. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21517. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21518. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21519. }
  21520. }
  21521. // Shadows
  21522. if (parsedData.shadowGenerators) {
  21523. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21524. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21525. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21526. }
  21527. }
  21528. // Actions (scene)
  21529. if (parsedData.actions) {
  21530. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21531. }
  21532. // Finish
  21533. return true;
  21534. }
  21535. });
  21536. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21537. })(BABYLON || (BABYLON = {}));
  21538. var BABYLON;
  21539. (function (BABYLON) {
  21540. var SpriteManager = (function () {
  21541. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21542. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21543. this.name = name;
  21544. this.cellSize = cellSize;
  21545. this.sprites = new Array();
  21546. this.renderingGroupId = 0;
  21547. this.layerMask = 0x0FFFFFFF;
  21548. this.fogEnabled = true;
  21549. this.isPickable = false;
  21550. this._vertexDeclaration = [4, 4, 4, 4];
  21551. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21552. this._capacity = capacity;
  21553. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21554. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21555. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21556. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21557. this._scene = scene;
  21558. this._scene.spriteManagers.push(this);
  21559. // VBO
  21560. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21561. var indices = [];
  21562. var index = 0;
  21563. for (var count = 0; count < capacity; count++) {
  21564. indices.push(index);
  21565. indices.push(index + 1);
  21566. indices.push(index + 2);
  21567. indices.push(index);
  21568. indices.push(index + 2);
  21569. indices.push(index + 3);
  21570. index += 4;
  21571. }
  21572. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21573. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21574. // Effects
  21575. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21576. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21577. }
  21578. Object.defineProperty(SpriteManager.prototype, "texture", {
  21579. get: function () {
  21580. return this._spriteTexture;
  21581. },
  21582. set: function (value) {
  21583. this._spriteTexture = value;
  21584. },
  21585. enumerable: true,
  21586. configurable: true
  21587. });
  21588. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21589. var arrayOffset = index * 16;
  21590. if (offsetX === 0)
  21591. offsetX = this._epsilon;
  21592. else if (offsetX === 1)
  21593. offsetX = 1 - this._epsilon;
  21594. if (offsetY === 0)
  21595. offsetY = this._epsilon;
  21596. else if (offsetY === 1)
  21597. offsetY = 1 - this._epsilon;
  21598. this._vertices[arrayOffset] = sprite.position.x;
  21599. this._vertices[arrayOffset + 1] = sprite.position.y;
  21600. this._vertices[arrayOffset + 2] = sprite.position.z;
  21601. this._vertices[arrayOffset + 3] = sprite.angle;
  21602. this._vertices[arrayOffset + 4] = sprite.width;
  21603. this._vertices[arrayOffset + 5] = sprite.height;
  21604. this._vertices[arrayOffset + 6] = offsetX;
  21605. this._vertices[arrayOffset + 7] = offsetY;
  21606. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21607. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21608. var offset = (sprite.cellIndex / rowSize) >> 0;
  21609. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21610. this._vertices[arrayOffset + 11] = offset;
  21611. // Color
  21612. this._vertices[arrayOffset + 12] = sprite.color.r;
  21613. this._vertices[arrayOffset + 13] = sprite.color.g;
  21614. this._vertices[arrayOffset + 14] = sprite.color.b;
  21615. this._vertices[arrayOffset + 15] = sprite.color.a;
  21616. };
  21617. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21618. var count = Math.min(this._capacity, this.sprites.length);
  21619. var min = BABYLON.Vector3.Zero();
  21620. var max = BABYLON.Vector3.Zero();
  21621. var distance = Number.MAX_VALUE;
  21622. var currentSprite;
  21623. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21624. var cameraView = camera.getViewMatrix();
  21625. for (var index = 0; index < count; index++) {
  21626. var sprite = this.sprites[index];
  21627. if (!sprite) {
  21628. continue;
  21629. }
  21630. if (predicate) {
  21631. if (!predicate(sprite)) {
  21632. continue;
  21633. }
  21634. }
  21635. else if (!sprite.isPickable) {
  21636. continue;
  21637. }
  21638. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21639. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21640. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21641. if (ray.intersectsBoxMinMax(min, max)) {
  21642. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21643. if (distance > currentDistance) {
  21644. distance = currentDistance;
  21645. currentSprite = sprite;
  21646. if (fastCheck) {
  21647. break;
  21648. }
  21649. }
  21650. }
  21651. }
  21652. if (currentSprite) {
  21653. var result = new BABYLON.PickingInfo();
  21654. result.hit = true;
  21655. result.pickedSprite = currentSprite;
  21656. result.distance = distance;
  21657. return result;
  21658. }
  21659. return null;
  21660. };
  21661. SpriteManager.prototype.render = function () {
  21662. // Check
  21663. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21664. return;
  21665. var engine = this._scene.getEngine();
  21666. var baseSize = this._spriteTexture.getBaseSize();
  21667. // Sprites
  21668. var deltaTime = engine.getDeltaTime();
  21669. var max = Math.min(this._capacity, this.sprites.length);
  21670. var rowSize = baseSize.width / this.cellSize;
  21671. var offset = 0;
  21672. for (var index = 0; index < max; index++) {
  21673. var sprite = this.sprites[index];
  21674. if (!sprite) {
  21675. continue;
  21676. }
  21677. sprite._animate(deltaTime);
  21678. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21679. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21680. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21681. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21682. }
  21683. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21684. // Render
  21685. var effect = this._effectBase;
  21686. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21687. effect = this._effectFog;
  21688. }
  21689. engine.enableEffect(effect);
  21690. var viewMatrix = this._scene.getViewMatrix();
  21691. effect.setTexture("diffuseSampler", this._spriteTexture);
  21692. effect.setMatrix("view", viewMatrix);
  21693. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21694. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21695. // Fog
  21696. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21697. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21698. effect.setColor3("vFogColor", this._scene.fogColor);
  21699. }
  21700. // VBOs
  21701. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21702. // Draw order
  21703. engine.setDepthFunctionToLessOrEqual();
  21704. effect.setBool("alphaTest", true);
  21705. engine.setColorWrite(false);
  21706. engine.draw(true, 0, max * 6);
  21707. engine.setColorWrite(true);
  21708. effect.setBool("alphaTest", false);
  21709. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21710. engine.draw(true, 0, max * 6);
  21711. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21712. };
  21713. SpriteManager.prototype.dispose = function () {
  21714. if (this._vertexBuffer) {
  21715. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21716. this._vertexBuffer = null;
  21717. }
  21718. if (this._indexBuffer) {
  21719. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21720. this._indexBuffer = null;
  21721. }
  21722. if (this._spriteTexture) {
  21723. this._spriteTexture.dispose();
  21724. this._spriteTexture = null;
  21725. }
  21726. // Remove from scene
  21727. var index = this._scene.spriteManagers.indexOf(this);
  21728. this._scene.spriteManagers.splice(index, 1);
  21729. // Callback
  21730. if (this.onDispose) {
  21731. this.onDispose();
  21732. }
  21733. };
  21734. return SpriteManager;
  21735. })();
  21736. BABYLON.SpriteManager = SpriteManager;
  21737. })(BABYLON || (BABYLON = {}));
  21738. var BABYLON;
  21739. (function (BABYLON) {
  21740. var Sprite = (function () {
  21741. function Sprite(name, manager) {
  21742. this.name = name;
  21743. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21744. this.width = 1.0;
  21745. this.height = 1.0;
  21746. this.angle = 0;
  21747. this.cellIndex = 0;
  21748. this.invertU = 0;
  21749. this.invertV = 0;
  21750. this.animations = new Array();
  21751. this.isPickable = false;
  21752. this._animationStarted = false;
  21753. this._loopAnimation = false;
  21754. this._fromIndex = 0;
  21755. this._toIndex = 0;
  21756. this._delay = 0;
  21757. this._direction = 1;
  21758. this._frameCount = 0;
  21759. this._time = 0;
  21760. this._manager = manager;
  21761. this._manager.sprites.push(this);
  21762. this.position = BABYLON.Vector3.Zero();
  21763. }
  21764. Object.defineProperty(Sprite.prototype, "size", {
  21765. get: function () {
  21766. return this.width;
  21767. },
  21768. set: function (value) {
  21769. this.width = value;
  21770. this.height = value;
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21776. this._fromIndex = from;
  21777. this._toIndex = to;
  21778. this._loopAnimation = loop;
  21779. this._delay = delay;
  21780. this._animationStarted = true;
  21781. this._direction = from < to ? 1 : -1;
  21782. this.cellIndex = from;
  21783. this._time = 0;
  21784. };
  21785. Sprite.prototype.stopAnimation = function () {
  21786. this._animationStarted = false;
  21787. };
  21788. Sprite.prototype._animate = function (deltaTime) {
  21789. if (!this._animationStarted)
  21790. return;
  21791. this._time += deltaTime;
  21792. if (this._time > this._delay) {
  21793. this._time = this._time % this._delay;
  21794. this.cellIndex += this._direction;
  21795. if (this.cellIndex == this._toIndex) {
  21796. if (this._loopAnimation) {
  21797. this.cellIndex = this._fromIndex;
  21798. }
  21799. else {
  21800. this._animationStarted = false;
  21801. if (this.disposeWhenFinishedAnimating) {
  21802. this.dispose();
  21803. }
  21804. }
  21805. }
  21806. }
  21807. };
  21808. Sprite.prototype.dispose = function () {
  21809. for (var i = 0; i < this._manager.sprites.length; i++) {
  21810. if (this._manager.sprites[i] == this) {
  21811. this._manager.sprites.splice(i, 1);
  21812. }
  21813. }
  21814. };
  21815. return Sprite;
  21816. })();
  21817. BABYLON.Sprite = Sprite;
  21818. })(BABYLON || (BABYLON = {}));
  21819. var BABYLON;
  21820. (function (BABYLON) {
  21821. var Layer = (function () {
  21822. function Layer(name, imgUrl, scene, isBackground, color) {
  21823. this.name = name;
  21824. this.scale = new BABYLON.Vector2(1, 1);
  21825. this.offset = new BABYLON.Vector2(0, 0);
  21826. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21827. this._vertexDeclaration = [2];
  21828. this._vertexStrideSize = 2 * 4;
  21829. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21830. this.isBackground = isBackground === undefined ? true : isBackground;
  21831. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21832. this._scene = scene;
  21833. this._scene.layers.push(this);
  21834. // VBO
  21835. var vertices = [];
  21836. vertices.push(1, 1);
  21837. vertices.push(-1, 1);
  21838. vertices.push(-1, -1);
  21839. vertices.push(1, -1);
  21840. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21841. // Indices
  21842. var indices = [];
  21843. indices.push(0);
  21844. indices.push(1);
  21845. indices.push(2);
  21846. indices.push(0);
  21847. indices.push(2);
  21848. indices.push(3);
  21849. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21850. // Effects
  21851. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21852. }
  21853. Layer.prototype.render = function () {
  21854. // Check
  21855. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21856. return;
  21857. var engine = this._scene.getEngine();
  21858. // Render
  21859. engine.enableEffect(this._effect);
  21860. engine.setState(false);
  21861. // Texture
  21862. this._effect.setTexture("textureSampler", this.texture);
  21863. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21864. // Color
  21865. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21866. // Scale / offset
  21867. this._effect.setVector2("offset", this.offset);
  21868. this._effect.setVector2("scale", this.scale);
  21869. // VBOs
  21870. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21871. // Draw order
  21872. engine.setAlphaMode(this.alphaBlendingMode);
  21873. engine.draw(true, 0, 6);
  21874. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21875. };
  21876. Layer.prototype.dispose = function () {
  21877. if (this._vertexBuffer) {
  21878. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21879. this._vertexBuffer = null;
  21880. }
  21881. if (this._indexBuffer) {
  21882. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21883. this._indexBuffer = null;
  21884. }
  21885. if (this.texture) {
  21886. this.texture.dispose();
  21887. this.texture = null;
  21888. }
  21889. // Remove from scene
  21890. var index = this._scene.layers.indexOf(this);
  21891. this._scene.layers.splice(index, 1);
  21892. // Callback
  21893. if (this.onDispose) {
  21894. this.onDispose();
  21895. }
  21896. };
  21897. return Layer;
  21898. })();
  21899. BABYLON.Layer = Layer;
  21900. })(BABYLON || (BABYLON = {}));
  21901. var BABYLON;
  21902. (function (BABYLON) {
  21903. var Particle = (function () {
  21904. function Particle() {
  21905. this.position = BABYLON.Vector3.Zero();
  21906. this.direction = BABYLON.Vector3.Zero();
  21907. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21908. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21909. this.lifeTime = 1.0;
  21910. this.age = 0;
  21911. this.size = 0;
  21912. this.angle = 0;
  21913. this.angularSpeed = 0;
  21914. }
  21915. Particle.prototype.copyTo = function (other) {
  21916. other.position.copyFrom(this.position);
  21917. other.direction.copyFrom(this.direction);
  21918. other.color.copyFrom(this.color);
  21919. other.colorStep.copyFrom(this.colorStep);
  21920. other.lifeTime = this.lifeTime;
  21921. other.age = this.age;
  21922. other.size = this.size;
  21923. other.angle = this.angle;
  21924. other.angularSpeed = this.angularSpeed;
  21925. };
  21926. return Particle;
  21927. })();
  21928. BABYLON.Particle = Particle;
  21929. })(BABYLON || (BABYLON = {}));
  21930. var BABYLON;
  21931. (function (BABYLON) {
  21932. var randomNumber = function (min, max) {
  21933. if (min === max) {
  21934. return (min);
  21935. }
  21936. var random = Math.random();
  21937. return ((random * (max - min)) + min);
  21938. };
  21939. var ParticleSystem = (function () {
  21940. function ParticleSystem(name, capacity, scene, customEffect) {
  21941. var _this = this;
  21942. this.name = name;
  21943. // Members
  21944. this.animations = [];
  21945. this.renderingGroupId = 0;
  21946. this.emitter = null;
  21947. this.emitRate = 10;
  21948. this.manualEmitCount = -1;
  21949. this.updateSpeed = 0.01;
  21950. this.targetStopDuration = 0;
  21951. this.disposeOnStop = false;
  21952. this.minEmitPower = 1;
  21953. this.maxEmitPower = 1;
  21954. this.minLifeTime = 1;
  21955. this.maxLifeTime = 1;
  21956. this.minSize = 1;
  21957. this.maxSize = 1;
  21958. this.minAngularSpeed = 0;
  21959. this.maxAngularSpeed = 0;
  21960. this.layerMask = 0x0FFFFFFF;
  21961. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21962. this.forceDepthWrite = false;
  21963. this.gravity = BABYLON.Vector3.Zero();
  21964. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21965. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21966. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21967. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21968. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21969. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21970. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21971. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21972. this.particles = new Array();
  21973. this._vertexDeclaration = [3, 4, 4];
  21974. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21975. this._stockParticles = new Array();
  21976. this._newPartsExcess = 0;
  21977. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21978. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21979. this._scaledDirection = BABYLON.Vector3.Zero();
  21980. this._scaledGravity = BABYLON.Vector3.Zero();
  21981. this._currentRenderId = -1;
  21982. this._started = false;
  21983. this._stopped = false;
  21984. this._actualFrame = 0;
  21985. this.id = name;
  21986. this._capacity = capacity;
  21987. this._scene = scene;
  21988. this._customEffect = customEffect;
  21989. scene.particleSystems.push(this);
  21990. // VBO
  21991. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21992. var indices = [];
  21993. var index = 0;
  21994. for (var count = 0; count < capacity; count++) {
  21995. indices.push(index);
  21996. indices.push(index + 1);
  21997. indices.push(index + 2);
  21998. indices.push(index);
  21999. indices.push(index + 2);
  22000. indices.push(index + 3);
  22001. index += 4;
  22002. }
  22003. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22004. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  22005. // Default behaviors
  22006. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  22007. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  22008. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  22009. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  22010. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  22011. };
  22012. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  22013. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  22014. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  22015. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  22016. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  22017. };
  22018. this.updateFunction = function (particles) {
  22019. for (var index = 0; index < particles.length; index++) {
  22020. var particle = particles[index];
  22021. particle.age += _this._scaledUpdateSpeed;
  22022. if (particle.age >= particle.lifeTime) {
  22023. _this.recycleParticle(particle);
  22024. index--;
  22025. continue;
  22026. }
  22027. else {
  22028. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  22029. particle.color.addInPlace(_this._scaledColorStep);
  22030. if (particle.color.a < 0)
  22031. particle.color.a = 0;
  22032. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  22033. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  22034. particle.position.addInPlace(_this._scaledDirection);
  22035. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  22036. particle.direction.addInPlace(_this._scaledGravity);
  22037. }
  22038. }
  22039. };
  22040. }
  22041. ParticleSystem.prototype.recycleParticle = function (particle) {
  22042. var lastParticle = this.particles.pop();
  22043. if (lastParticle !== particle) {
  22044. lastParticle.copyTo(particle);
  22045. this._stockParticles.push(lastParticle);
  22046. }
  22047. };
  22048. ParticleSystem.prototype.getCapacity = function () {
  22049. return this._capacity;
  22050. };
  22051. ParticleSystem.prototype.isAlive = function () {
  22052. return this._alive;
  22053. };
  22054. ParticleSystem.prototype.isStarted = function () {
  22055. return this._started;
  22056. };
  22057. ParticleSystem.prototype.start = function () {
  22058. this._started = true;
  22059. this._stopped = false;
  22060. this._actualFrame = 0;
  22061. };
  22062. ParticleSystem.prototype.stop = function () {
  22063. this._stopped = true;
  22064. };
  22065. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  22066. var offset = index * 11;
  22067. this._vertices[offset] = particle.position.x;
  22068. this._vertices[offset + 1] = particle.position.y;
  22069. this._vertices[offset + 2] = particle.position.z;
  22070. this._vertices[offset + 3] = particle.color.r;
  22071. this._vertices[offset + 4] = particle.color.g;
  22072. this._vertices[offset + 5] = particle.color.b;
  22073. this._vertices[offset + 6] = particle.color.a;
  22074. this._vertices[offset + 7] = particle.angle;
  22075. this._vertices[offset + 8] = particle.size;
  22076. this._vertices[offset + 9] = offsetX;
  22077. this._vertices[offset + 10] = offsetY;
  22078. };
  22079. ParticleSystem.prototype._update = function (newParticles) {
  22080. // Update current
  22081. this._alive = this.particles.length > 0;
  22082. this.updateFunction(this.particles);
  22083. // Add new ones
  22084. var worldMatrix;
  22085. if (this.emitter.position) {
  22086. worldMatrix = this.emitter.getWorldMatrix();
  22087. }
  22088. else {
  22089. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  22090. }
  22091. var particle;
  22092. for (var index = 0; index < newParticles; index++) {
  22093. if (this.particles.length === this._capacity) {
  22094. break;
  22095. }
  22096. if (this._stockParticles.length !== 0) {
  22097. particle = this._stockParticles.pop();
  22098. particle.age = 0;
  22099. }
  22100. else {
  22101. particle = new BABYLON.Particle();
  22102. }
  22103. this.particles.push(particle);
  22104. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  22105. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  22106. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  22107. particle.size = randomNumber(this.minSize, this.maxSize);
  22108. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  22109. this.startPositionFunction(worldMatrix, particle.position, particle);
  22110. var step = randomNumber(0, 1.0);
  22111. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  22112. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  22113. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  22114. }
  22115. };
  22116. ParticleSystem.prototype._getEffect = function () {
  22117. if (this._customEffect) {
  22118. return this._customEffect;
  22119. }
  22120. ;
  22121. var defines = [];
  22122. if (this._scene.clipPlane) {
  22123. defines.push("#define CLIPPLANE");
  22124. }
  22125. // Effect
  22126. var join = defines.join("\n");
  22127. if (this._cachedDefines !== join) {
  22128. this._cachedDefines = join;
  22129. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  22130. }
  22131. return this._effect;
  22132. };
  22133. ParticleSystem.prototype.animate = function () {
  22134. if (!this._started)
  22135. return;
  22136. var effect = this._getEffect();
  22137. // Check
  22138. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22139. return;
  22140. if (this._currentRenderId === this._scene.getRenderId()) {
  22141. return;
  22142. }
  22143. this._currentRenderId = this._scene.getRenderId();
  22144. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22145. // determine the number of particles we need to create
  22146. var newParticles;
  22147. if (this.manualEmitCount > -1) {
  22148. newParticles = this.manualEmitCount;
  22149. this._newPartsExcess = 0;
  22150. this.manualEmitCount = 0;
  22151. }
  22152. else {
  22153. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  22154. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  22155. }
  22156. if (this._newPartsExcess > 1.0) {
  22157. newParticles += this._newPartsExcess >> 0;
  22158. this._newPartsExcess -= this._newPartsExcess >> 0;
  22159. }
  22160. this._alive = false;
  22161. if (!this._stopped) {
  22162. this._actualFrame += this._scaledUpdateSpeed;
  22163. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22164. this.stop();
  22165. }
  22166. else {
  22167. newParticles = 0;
  22168. }
  22169. this._update(newParticles);
  22170. // Stopped?
  22171. if (this._stopped) {
  22172. if (!this._alive) {
  22173. this._started = false;
  22174. if (this.disposeOnStop) {
  22175. this._scene._toBeDisposed.push(this);
  22176. }
  22177. }
  22178. }
  22179. // Update VBO
  22180. var offset = 0;
  22181. for (var index = 0; index < this.particles.length; index++) {
  22182. var particle = this.particles[index];
  22183. this._appendParticleVertex(offset++, particle, 0, 0);
  22184. this._appendParticleVertex(offset++, particle, 1, 0);
  22185. this._appendParticleVertex(offset++, particle, 1, 1);
  22186. this._appendParticleVertex(offset++, particle, 0, 1);
  22187. }
  22188. var engine = this._scene.getEngine();
  22189. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22190. };
  22191. ParticleSystem.prototype.render = function () {
  22192. var effect = this._getEffect();
  22193. // Check
  22194. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22195. return 0;
  22196. var engine = this._scene.getEngine();
  22197. // Render
  22198. engine.enableEffect(effect);
  22199. engine.setState(false);
  22200. var viewMatrix = this._scene.getViewMatrix();
  22201. effect.setTexture("diffuseSampler", this.particleTexture);
  22202. effect.setMatrix("view", viewMatrix);
  22203. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22204. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22205. if (this._scene.clipPlane) {
  22206. var clipPlane = this._scene.clipPlane;
  22207. var invView = viewMatrix.clone();
  22208. invView.invert();
  22209. effect.setMatrix("invView", invView);
  22210. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22211. }
  22212. // VBOs
  22213. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22214. // Draw order
  22215. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22216. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22217. }
  22218. else {
  22219. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22220. }
  22221. if (this.forceDepthWrite) {
  22222. engine.setDepthWrite(true);
  22223. }
  22224. engine.draw(true, 0, this.particles.length * 6);
  22225. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22226. return this.particles.length;
  22227. };
  22228. ParticleSystem.prototype.dispose = function () {
  22229. if (this._vertexBuffer) {
  22230. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22231. this._vertexBuffer = null;
  22232. }
  22233. if (this._indexBuffer) {
  22234. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22235. this._indexBuffer = null;
  22236. }
  22237. if (this.particleTexture) {
  22238. this.particleTexture.dispose();
  22239. this.particleTexture = null;
  22240. }
  22241. // Remove from scene
  22242. var index = this._scene.particleSystems.indexOf(this);
  22243. this._scene.particleSystems.splice(index, 1);
  22244. // Callback
  22245. if (this.onDispose) {
  22246. this.onDispose();
  22247. }
  22248. };
  22249. // Clone
  22250. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22251. var result = new ParticleSystem(name, this._capacity, this._scene);
  22252. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22253. if (newEmitter === undefined) {
  22254. newEmitter = this.emitter;
  22255. }
  22256. result.emitter = newEmitter;
  22257. if (this.particleTexture) {
  22258. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22259. }
  22260. result.start();
  22261. return result;
  22262. };
  22263. ParticleSystem.prototype.serialize = function () {
  22264. var serializationObject = {};
  22265. serializationObject.name = this.name;
  22266. serializationObject.id = this.id;
  22267. // Emitter
  22268. if (this.emitter.position) {
  22269. serializationObject.emitterId = this.emitter.id;
  22270. }
  22271. else {
  22272. serializationObject.emitter = this.emitter.asArray();
  22273. }
  22274. serializationObject.capacity = this.getCapacity();
  22275. if (this.particleTexture) {
  22276. serializationObject.textureName = this.particleTexture.name;
  22277. }
  22278. // Animations
  22279. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22280. // Particle system
  22281. serializationObject.minAngularSpeed = this.minAngularSpeed;
  22282. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  22283. serializationObject.minSize = this.minSize;
  22284. serializationObject.maxSize = this.maxSize;
  22285. serializationObject.minEmitPower = this.minEmitPower;
  22286. serializationObject.maxEmitPower = this.maxEmitPower;
  22287. serializationObject.minLifeTime = this.minLifeTime;
  22288. serializationObject.maxLifeTime = this.maxLifeTime;
  22289. serializationObject.emitRate = this.emitRate;
  22290. serializationObject.minEmitBox = this.minEmitBox.asArray();
  22291. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  22292. serializationObject.gravity = this.gravity.asArray();
  22293. serializationObject.direction1 = this.direction1.asArray();
  22294. serializationObject.direction2 = this.direction2.asArray();
  22295. serializationObject.color1 = this.color1.asArray();
  22296. serializationObject.color2 = this.color2.asArray();
  22297. serializationObject.colorDead = this.colorDead.asArray();
  22298. serializationObject.updateSpeed = this.updateSpeed;
  22299. serializationObject.targetStopDuration = this.targetStopDuration;
  22300. serializationObject.textureMask = this.textureMask.asArray();
  22301. serializationObject.blendMode = this.blendMode;
  22302. return serializationObject;
  22303. };
  22304. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  22305. var name = parsedParticleSystem.name;
  22306. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  22307. if (parsedParticleSystem.id) {
  22308. particleSystem.id = parsedParticleSystem.id;
  22309. }
  22310. // Texture
  22311. if (parsedParticleSystem.textureName) {
  22312. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  22313. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  22314. }
  22315. // Emitter
  22316. if (parsedParticleSystem.emitterId) {
  22317. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  22318. }
  22319. else {
  22320. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  22321. }
  22322. // Animations
  22323. if (parsedParticleSystem.animations) {
  22324. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  22325. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  22326. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22327. }
  22328. }
  22329. // Particle system
  22330. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  22331. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  22332. particleSystem.minSize = parsedParticleSystem.minSize;
  22333. particleSystem.maxSize = parsedParticleSystem.maxSize;
  22334. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  22335. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  22336. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  22337. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  22338. particleSystem.emitRate = parsedParticleSystem.emitRate;
  22339. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  22340. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  22341. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  22342. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  22343. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  22344. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  22345. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  22346. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  22347. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  22348. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  22349. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  22350. particleSystem.blendMode = parsedParticleSystem.blendMode;
  22351. particleSystem.start();
  22352. return particleSystem;
  22353. };
  22354. // Statics
  22355. ParticleSystem.BLENDMODE_ONEONE = 0;
  22356. ParticleSystem.BLENDMODE_STANDARD = 1;
  22357. return ParticleSystem;
  22358. })();
  22359. BABYLON.ParticleSystem = ParticleSystem;
  22360. })(BABYLON || (BABYLON = {}));
  22361. var BABYLON;
  22362. (function (BABYLON) {
  22363. var AnimationRange = (function () {
  22364. function AnimationRange(name, from, to) {
  22365. this.name = name;
  22366. this.from = from;
  22367. this.to = to;
  22368. }
  22369. return AnimationRange;
  22370. })();
  22371. BABYLON.AnimationRange = AnimationRange;
  22372. /**
  22373. * Composed of a frame, and an action function
  22374. */
  22375. var AnimationEvent = (function () {
  22376. function AnimationEvent(frame, action, onlyOnce) {
  22377. this.frame = frame;
  22378. this.action = action;
  22379. this.onlyOnce = onlyOnce;
  22380. this.isDone = false;
  22381. }
  22382. return AnimationEvent;
  22383. })();
  22384. BABYLON.AnimationEvent = AnimationEvent;
  22385. var Animation = (function () {
  22386. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  22387. this.name = name;
  22388. this.targetProperty = targetProperty;
  22389. this.framePerSecond = framePerSecond;
  22390. this.dataType = dataType;
  22391. this.loopMode = loopMode;
  22392. this.enableBlending = enableBlending;
  22393. this._offsetsCache = {};
  22394. this._highLimitsCache = {};
  22395. this._stopped = false;
  22396. this._blendingFactor = 0;
  22397. // The set of event that will be linked to this animation
  22398. this._events = new Array();
  22399. this.allowMatricesInterpolation = false;
  22400. this.blendingSpeed = 0.01;
  22401. this._ranges = {};
  22402. this.targetPropertyPath = targetProperty.split(".");
  22403. this.dataType = dataType;
  22404. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22405. }
  22406. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22407. var dataType = undefined;
  22408. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22409. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22410. }
  22411. else if (from instanceof BABYLON.Quaternion) {
  22412. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22413. }
  22414. else if (from instanceof BABYLON.Vector3) {
  22415. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22416. }
  22417. else if (from instanceof BABYLON.Vector2) {
  22418. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22419. }
  22420. else if (from instanceof BABYLON.Color3) {
  22421. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22422. }
  22423. if (dataType == undefined) {
  22424. return null;
  22425. }
  22426. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22427. var keys = [];
  22428. keys.push({ frame: 0, value: from });
  22429. keys.push({ frame: totalFrame, value: to });
  22430. animation.setKeys(keys);
  22431. if (easingFunction !== undefined) {
  22432. animation.setEasingFunction(easingFunction);
  22433. }
  22434. return animation;
  22435. };
  22436. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22437. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22438. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22439. };
  22440. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22441. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22442. node.animations.push(animation);
  22443. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22444. };
  22445. // Methods
  22446. /**
  22447. * Add an event to this animation.
  22448. */
  22449. Animation.prototype.addEvent = function (event) {
  22450. this._events.push(event);
  22451. };
  22452. /**
  22453. * Remove all events found at the given frame
  22454. * @param frame
  22455. */
  22456. Animation.prototype.removeEvents = function (frame) {
  22457. for (var index = 0; index < this._events.length; index++) {
  22458. if (this._events[index].frame === frame) {
  22459. this._events.splice(index, 1);
  22460. index--;
  22461. }
  22462. }
  22463. };
  22464. Animation.prototype.createRange = function (name, from, to) {
  22465. // check name not already in use; could happen for bones after serialized
  22466. if (!this._ranges[name]) {
  22467. this._ranges[name] = new AnimationRange(name, from, to);
  22468. }
  22469. };
  22470. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22471. if (deleteFrames === void 0) { deleteFrames = true; }
  22472. if (this._ranges[name]) {
  22473. if (deleteFrames) {
  22474. var from = this._ranges[name].from;
  22475. var to = this._ranges[name].to;
  22476. // this loop MUST go high to low for multiple splices to work
  22477. for (var key = this._keys.length - 1; key >= 0; key--) {
  22478. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22479. this._keys.splice(key, 1);
  22480. }
  22481. }
  22482. }
  22483. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22484. }
  22485. };
  22486. Animation.prototype.getRange = function (name) {
  22487. return this._ranges[name];
  22488. };
  22489. Animation.prototype.reset = function () {
  22490. this._offsetsCache = {};
  22491. this._highLimitsCache = {};
  22492. this.currentFrame = 0;
  22493. this._blendingFactor = 0;
  22494. this._originalBlendValue = null;
  22495. };
  22496. Animation.prototype.isStopped = function () {
  22497. return this._stopped;
  22498. };
  22499. Animation.prototype.getKeys = function () {
  22500. return this._keys;
  22501. };
  22502. Animation.prototype.getHighestFrame = function () {
  22503. var ret = 0;
  22504. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22505. if (ret < this._keys[key].frame) {
  22506. ret = this._keys[key].frame;
  22507. }
  22508. }
  22509. return ret;
  22510. };
  22511. Animation.prototype.getEasingFunction = function () {
  22512. return this._easingFunction;
  22513. };
  22514. Animation.prototype.setEasingFunction = function (easingFunction) {
  22515. this._easingFunction = easingFunction;
  22516. };
  22517. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22518. return startValue + (endValue - startValue) * gradient;
  22519. };
  22520. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22521. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22522. };
  22523. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22524. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22525. };
  22526. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22527. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22528. };
  22529. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22530. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22531. };
  22532. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22533. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22534. };
  22535. Animation.prototype.clone = function () {
  22536. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22537. if (this._keys) {
  22538. clone.setKeys(this._keys);
  22539. }
  22540. return clone;
  22541. };
  22542. Animation.prototype.setKeys = function (values) {
  22543. this._keys = values.slice(0);
  22544. this._offsetsCache = {};
  22545. this._highLimitsCache = {};
  22546. };
  22547. Animation.prototype._getKeyValue = function (value) {
  22548. if (typeof value === "function") {
  22549. return value();
  22550. }
  22551. return value;
  22552. };
  22553. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22554. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22555. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22556. }
  22557. this.currentFrame = currentFrame;
  22558. // Try to get a hash to find the right key
  22559. 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));
  22560. if (this._keys[startKey].frame >= currentFrame) {
  22561. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22562. startKey--;
  22563. }
  22564. }
  22565. for (var key = startKey; key < this._keys.length; key++) {
  22566. if (this._keys[key + 1].frame >= currentFrame) {
  22567. var startValue = this._getKeyValue(this._keys[key].value);
  22568. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22569. // gradient : percent of currentFrame between the frame inf and the frame sup
  22570. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22571. // check for easingFunction and correction of gradient
  22572. if (this._easingFunction != null) {
  22573. gradient = this._easingFunction.ease(gradient);
  22574. }
  22575. switch (this.dataType) {
  22576. // Float
  22577. case Animation.ANIMATIONTYPE_FLOAT:
  22578. switch (loopMode) {
  22579. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22580. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22581. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22582. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22583. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22584. }
  22585. break;
  22586. // Quaternion
  22587. case Animation.ANIMATIONTYPE_QUATERNION:
  22588. var quaternion = null;
  22589. switch (loopMode) {
  22590. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22591. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22592. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22593. break;
  22594. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22595. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22596. break;
  22597. }
  22598. return quaternion;
  22599. // Vector3
  22600. case Animation.ANIMATIONTYPE_VECTOR3:
  22601. switch (loopMode) {
  22602. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22603. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22604. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22605. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22606. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22607. }
  22608. // Vector2
  22609. case Animation.ANIMATIONTYPE_VECTOR2:
  22610. switch (loopMode) {
  22611. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22612. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22613. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22614. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22615. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22616. }
  22617. // Color3
  22618. case Animation.ANIMATIONTYPE_COLOR3:
  22619. switch (loopMode) {
  22620. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22621. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22622. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22623. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22624. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22625. }
  22626. // Matrix
  22627. case Animation.ANIMATIONTYPE_MATRIX:
  22628. switch (loopMode) {
  22629. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22630. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22631. if (this.allowMatricesInterpolation) {
  22632. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22633. }
  22634. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22635. return startValue;
  22636. }
  22637. default:
  22638. break;
  22639. }
  22640. break;
  22641. }
  22642. }
  22643. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22644. };
  22645. Animation.prototype.setValue = function (currentValue, blend) {
  22646. if (blend === void 0) { blend = false; }
  22647. // Set value
  22648. var path;
  22649. var destination;
  22650. if (this.targetPropertyPath.length > 1) {
  22651. var property = this._target[this.targetPropertyPath[0]];
  22652. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22653. property = property[this.targetPropertyPath[index]];
  22654. }
  22655. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  22656. destination = property;
  22657. }
  22658. else {
  22659. path = this.targetPropertyPath[0];
  22660. destination = this._target;
  22661. }
  22662. // Blending
  22663. if (this.enableBlending && this._blendingFactor <= 1.0) {
  22664. if (!this._originalBlendValue) {
  22665. this._originalBlendValue = destination[path];
  22666. }
  22667. if (this._originalBlendValue.prototype) {
  22668. if (this._originalBlendValue.prototype.Lerp) {
  22669. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  22670. }
  22671. else {
  22672. destination[path] = currentValue;
  22673. }
  22674. }
  22675. else {
  22676. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  22677. }
  22678. this._blendingFactor += this.blendingSpeed;
  22679. }
  22680. else {
  22681. destination[path] = currentValue;
  22682. }
  22683. if (this._target.markAsDirty) {
  22684. this._target.markAsDirty(this.targetProperty);
  22685. }
  22686. };
  22687. Animation.prototype.goToFrame = function (frame) {
  22688. if (frame < this._keys[0].frame) {
  22689. frame = this._keys[0].frame;
  22690. }
  22691. else if (frame > this._keys[this._keys.length - 1].frame) {
  22692. frame = this._keys[this._keys.length - 1].frame;
  22693. }
  22694. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22695. this.setValue(currentValue);
  22696. };
  22697. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  22698. if (blend === void 0) { blend = false; }
  22699. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22700. this._stopped = true;
  22701. return false;
  22702. }
  22703. var returnValue = true;
  22704. // Adding a start key at frame 0 if missing
  22705. if (this._keys[0].frame !== 0) {
  22706. var newKey = { frame: 0, value: this._keys[0].value };
  22707. this._keys.splice(0, 0, newKey);
  22708. }
  22709. // Check limits
  22710. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22711. from = this._keys[0].frame;
  22712. }
  22713. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22714. to = this._keys[this._keys.length - 1].frame;
  22715. }
  22716. // Compute ratio
  22717. var range = to - from;
  22718. var offsetValue;
  22719. // ratio represents the frame delta between from and to
  22720. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22721. var highLimitValue = 0;
  22722. if (ratio > range && !loop) {
  22723. returnValue = false;
  22724. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22725. }
  22726. else {
  22727. // Get max value if required
  22728. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22729. var keyOffset = to.toString() + from.toString();
  22730. if (!this._offsetsCache[keyOffset]) {
  22731. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22732. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22733. switch (this.dataType) {
  22734. // Float
  22735. case Animation.ANIMATIONTYPE_FLOAT:
  22736. this._offsetsCache[keyOffset] = toValue - fromValue;
  22737. break;
  22738. // Quaternion
  22739. case Animation.ANIMATIONTYPE_QUATERNION:
  22740. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22741. break;
  22742. // Vector3
  22743. case Animation.ANIMATIONTYPE_VECTOR3:
  22744. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22745. // Vector2
  22746. case Animation.ANIMATIONTYPE_VECTOR2:
  22747. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22748. // Color3
  22749. case Animation.ANIMATIONTYPE_COLOR3:
  22750. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22751. default:
  22752. break;
  22753. }
  22754. this._highLimitsCache[keyOffset] = toValue;
  22755. }
  22756. highLimitValue = this._highLimitsCache[keyOffset];
  22757. offsetValue = this._offsetsCache[keyOffset];
  22758. }
  22759. }
  22760. if (offsetValue === undefined) {
  22761. switch (this.dataType) {
  22762. // Float
  22763. case Animation.ANIMATIONTYPE_FLOAT:
  22764. offsetValue = 0;
  22765. break;
  22766. // Quaternion
  22767. case Animation.ANIMATIONTYPE_QUATERNION:
  22768. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22769. break;
  22770. // Vector3
  22771. case Animation.ANIMATIONTYPE_VECTOR3:
  22772. offsetValue = BABYLON.Vector3.Zero();
  22773. break;
  22774. // Vector2
  22775. case Animation.ANIMATIONTYPE_VECTOR2:
  22776. offsetValue = BABYLON.Vector2.Zero();
  22777. break;
  22778. // Color3
  22779. case Animation.ANIMATIONTYPE_COLOR3:
  22780. offsetValue = BABYLON.Color3.Black();
  22781. }
  22782. }
  22783. // Compute value
  22784. var repeatCount = (ratio / range) >> 0;
  22785. var currentFrame = returnValue ? from + ratio % range : to;
  22786. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22787. // Set value
  22788. this.setValue(currentValue);
  22789. // Check events
  22790. for (var index = 0; index < this._events.length; index++) {
  22791. if (currentFrame >= this._events[index].frame) {
  22792. var event = this._events[index];
  22793. if (!event.isDone) {
  22794. // If event should be done only once, remove it.
  22795. if (event.onlyOnce) {
  22796. this._events.splice(index, 1);
  22797. index--;
  22798. }
  22799. event.isDone = true;
  22800. event.action();
  22801. } // Don't do anything if the event has already be done.
  22802. }
  22803. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22804. // reset event, the animation is looping
  22805. this._events[index].isDone = false;
  22806. }
  22807. }
  22808. if (!returnValue) {
  22809. this._stopped = true;
  22810. }
  22811. return returnValue;
  22812. };
  22813. Animation.prototype.serialize = function () {
  22814. var serializationObject = {};
  22815. serializationObject.name = this.name;
  22816. serializationObject.property = this.targetProperty;
  22817. serializationObject.framePerSecond = this.framePerSecond;
  22818. serializationObject.dataType = this.dataType;
  22819. serializationObject.loopBehavior = this.loopMode;
  22820. var dataType = this.dataType;
  22821. serializationObject.keys = [];
  22822. var keys = this.getKeys();
  22823. for (var index = 0; index < keys.length; index++) {
  22824. var animationKey = keys[index];
  22825. var key = {};
  22826. key.frame = animationKey.frame;
  22827. switch (dataType) {
  22828. case Animation.ANIMATIONTYPE_FLOAT:
  22829. key.values = [animationKey.value];
  22830. break;
  22831. case Animation.ANIMATIONTYPE_QUATERNION:
  22832. case Animation.ANIMATIONTYPE_MATRIX:
  22833. case Animation.ANIMATIONTYPE_VECTOR3:
  22834. case Animation.ANIMATIONTYPE_COLOR3:
  22835. key.values = animationKey.value.asArray();
  22836. break;
  22837. }
  22838. serializationObject.keys.push(key);
  22839. }
  22840. serializationObject.ranges = [];
  22841. for (var name in this._ranges) {
  22842. var range = {};
  22843. range.name = name;
  22844. range.from = this._ranges[name].from;
  22845. range.to = this._ranges[name].to;
  22846. serializationObject.ranges.push(range);
  22847. }
  22848. return serializationObject;
  22849. };
  22850. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22851. get: function () {
  22852. return Animation._ANIMATIONTYPE_FLOAT;
  22853. },
  22854. enumerable: true,
  22855. configurable: true
  22856. });
  22857. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22858. get: function () {
  22859. return Animation._ANIMATIONTYPE_VECTOR3;
  22860. },
  22861. enumerable: true,
  22862. configurable: true
  22863. });
  22864. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22865. get: function () {
  22866. return Animation._ANIMATIONTYPE_VECTOR2;
  22867. },
  22868. enumerable: true,
  22869. configurable: true
  22870. });
  22871. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22872. get: function () {
  22873. return Animation._ANIMATIONTYPE_QUATERNION;
  22874. },
  22875. enumerable: true,
  22876. configurable: true
  22877. });
  22878. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22879. get: function () {
  22880. return Animation._ANIMATIONTYPE_MATRIX;
  22881. },
  22882. enumerable: true,
  22883. configurable: true
  22884. });
  22885. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22886. get: function () {
  22887. return Animation._ANIMATIONTYPE_COLOR3;
  22888. },
  22889. enumerable: true,
  22890. configurable: true
  22891. });
  22892. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22893. get: function () {
  22894. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22895. },
  22896. enumerable: true,
  22897. configurable: true
  22898. });
  22899. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22900. get: function () {
  22901. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22902. },
  22903. enumerable: true,
  22904. configurable: true
  22905. });
  22906. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22907. get: function () {
  22908. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22909. },
  22910. enumerable: true,
  22911. configurable: true
  22912. });
  22913. Animation.Parse = function (parsedAnimation) {
  22914. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22915. var dataType = parsedAnimation.dataType;
  22916. var keys = [];
  22917. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22918. var key = parsedAnimation.keys[index];
  22919. var data;
  22920. switch (dataType) {
  22921. case Animation.ANIMATIONTYPE_FLOAT:
  22922. data = key.values[0];
  22923. break;
  22924. case Animation.ANIMATIONTYPE_QUATERNION:
  22925. data = BABYLON.Quaternion.FromArray(key.values);
  22926. break;
  22927. case Animation.ANIMATIONTYPE_MATRIX:
  22928. data = BABYLON.Matrix.FromArray(key.values);
  22929. break;
  22930. case Animation.ANIMATIONTYPE_COLOR3:
  22931. data = BABYLON.Color3.FromArray(key.values);
  22932. break;
  22933. case Animation.ANIMATIONTYPE_VECTOR3:
  22934. default:
  22935. data = BABYLON.Vector3.FromArray(key.values);
  22936. break;
  22937. }
  22938. keys.push({
  22939. frame: key.frame,
  22940. value: data
  22941. });
  22942. }
  22943. animation.setKeys(keys);
  22944. if (parsedAnimation.ranges) {
  22945. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22946. data = parsedAnimation.ranges[index];
  22947. animation.createRange(data.name, data.from, data.to);
  22948. }
  22949. }
  22950. return animation;
  22951. };
  22952. Animation.AppendSerializedAnimations = function (source, destination) {
  22953. if (source.animations) {
  22954. destination.animations = [];
  22955. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22956. var animation = source.animations[animationIndex];
  22957. destination.animations.push(animation.serialize());
  22958. }
  22959. }
  22960. };
  22961. // Statics
  22962. Animation._ANIMATIONTYPE_FLOAT = 0;
  22963. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22964. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22965. Animation._ANIMATIONTYPE_MATRIX = 3;
  22966. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22967. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22968. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22969. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22970. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22971. return Animation;
  22972. })();
  22973. BABYLON.Animation = Animation;
  22974. })(BABYLON || (BABYLON = {}));
  22975. var BABYLON;
  22976. (function (BABYLON) {
  22977. var Animatable = (function () {
  22978. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22979. if (fromFrame === void 0) { fromFrame = 0; }
  22980. if (toFrame === void 0) { toFrame = 100; }
  22981. if (loopAnimation === void 0) { loopAnimation = false; }
  22982. if (speedRatio === void 0) { speedRatio = 1.0; }
  22983. this.target = target;
  22984. this.fromFrame = fromFrame;
  22985. this.toFrame = toFrame;
  22986. this.loopAnimation = loopAnimation;
  22987. this.speedRatio = speedRatio;
  22988. this.onAnimationEnd = onAnimationEnd;
  22989. this._animations = new Array();
  22990. this._paused = false;
  22991. this.animationStarted = false;
  22992. if (animations) {
  22993. this.appendAnimations(target, animations);
  22994. }
  22995. this._scene = scene;
  22996. scene._activeAnimatables.push(this);
  22997. }
  22998. // Methods
  22999. Animatable.prototype.getAnimations = function () {
  23000. return this._animations;
  23001. };
  23002. Animatable.prototype.appendAnimations = function (target, animations) {
  23003. for (var index = 0; index < animations.length; index++) {
  23004. var animation = animations[index];
  23005. animation._target = target;
  23006. this._animations.push(animation);
  23007. }
  23008. };
  23009. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  23010. var animations = this._animations;
  23011. for (var index = 0; index < animations.length; index++) {
  23012. if (animations[index].targetProperty === property) {
  23013. return animations[index];
  23014. }
  23015. }
  23016. return null;
  23017. };
  23018. Animatable.prototype.reset = function () {
  23019. var animations = this._animations;
  23020. for (var index = 0; index < animations.length; index++) {
  23021. animations[index].reset();
  23022. }
  23023. this._localDelayOffset = null;
  23024. this._pausedDelay = null;
  23025. };
  23026. Animatable.prototype.goToFrame = function (frame) {
  23027. var animations = this._animations;
  23028. for (var index = 0; index < animations.length; index++) {
  23029. animations[index].goToFrame(frame);
  23030. }
  23031. };
  23032. Animatable.prototype.pause = function () {
  23033. if (this._paused) {
  23034. return;
  23035. }
  23036. this._paused = true;
  23037. };
  23038. Animatable.prototype.restart = function () {
  23039. this._paused = false;
  23040. };
  23041. Animatable.prototype.stop = function () {
  23042. var index = this._scene._activeAnimatables.indexOf(this);
  23043. if (index > -1) {
  23044. this._scene._activeAnimatables.splice(index, 1);
  23045. if (this.onAnimationEnd) {
  23046. this.onAnimationEnd();
  23047. }
  23048. }
  23049. };
  23050. Animatable.prototype._animate = function (delay) {
  23051. if (this._paused) {
  23052. this.animationStarted = false;
  23053. if (!this._pausedDelay) {
  23054. this._pausedDelay = delay;
  23055. }
  23056. return true;
  23057. }
  23058. if (!this._localDelayOffset) {
  23059. this._localDelayOffset = delay;
  23060. }
  23061. else if (this._pausedDelay) {
  23062. this._localDelayOffset += delay - this._pausedDelay;
  23063. this._pausedDelay = null;
  23064. }
  23065. // Animating
  23066. var running = false;
  23067. var animations = this._animations;
  23068. var index;
  23069. for (index = 0; index < animations.length; index++) {
  23070. var animation = animations[index];
  23071. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  23072. running = running || isRunning;
  23073. }
  23074. this.animationStarted = running;
  23075. if (!running) {
  23076. // Remove from active animatables
  23077. index = this._scene._activeAnimatables.indexOf(this);
  23078. this._scene._activeAnimatables.splice(index, 1);
  23079. }
  23080. if (!running && this.onAnimationEnd) {
  23081. this.onAnimationEnd();
  23082. this.onAnimationEnd = null;
  23083. }
  23084. return running;
  23085. };
  23086. return Animatable;
  23087. })();
  23088. BABYLON.Animatable = Animatable;
  23089. })(BABYLON || (BABYLON = {}));
  23090. var BABYLON;
  23091. (function (BABYLON) {
  23092. var EasingFunction = (function () {
  23093. function EasingFunction() {
  23094. // Properties
  23095. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  23096. }
  23097. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  23098. get: function () {
  23099. return EasingFunction._EASINGMODE_EASEIN;
  23100. },
  23101. enumerable: true,
  23102. configurable: true
  23103. });
  23104. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  23105. get: function () {
  23106. return EasingFunction._EASINGMODE_EASEOUT;
  23107. },
  23108. enumerable: true,
  23109. configurable: true
  23110. });
  23111. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  23112. get: function () {
  23113. return EasingFunction._EASINGMODE_EASEINOUT;
  23114. },
  23115. enumerable: true,
  23116. configurable: true
  23117. });
  23118. EasingFunction.prototype.setEasingMode = function (easingMode) {
  23119. var n = Math.min(Math.max(easingMode, 0), 2);
  23120. this._easingMode = n;
  23121. };
  23122. EasingFunction.prototype.getEasingMode = function () {
  23123. return this._easingMode;
  23124. };
  23125. EasingFunction.prototype.easeInCore = function (gradient) {
  23126. throw new Error('You must implement this method');
  23127. };
  23128. EasingFunction.prototype.ease = function (gradient) {
  23129. switch (this._easingMode) {
  23130. case EasingFunction.EASINGMODE_EASEIN:
  23131. return this.easeInCore(gradient);
  23132. case EasingFunction.EASINGMODE_EASEOUT:
  23133. return (1 - this.easeInCore(1 - gradient));
  23134. }
  23135. if (gradient >= 0.5) {
  23136. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  23137. }
  23138. return (this.easeInCore(gradient * 2) * 0.5);
  23139. };
  23140. //Statics
  23141. EasingFunction._EASINGMODE_EASEIN = 0;
  23142. EasingFunction._EASINGMODE_EASEOUT = 1;
  23143. EasingFunction._EASINGMODE_EASEINOUT = 2;
  23144. return EasingFunction;
  23145. })();
  23146. BABYLON.EasingFunction = EasingFunction;
  23147. var CircleEase = (function (_super) {
  23148. __extends(CircleEase, _super);
  23149. function CircleEase() {
  23150. _super.apply(this, arguments);
  23151. }
  23152. CircleEase.prototype.easeInCore = function (gradient) {
  23153. gradient = Math.max(0, Math.min(1, gradient));
  23154. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  23155. };
  23156. return CircleEase;
  23157. })(EasingFunction);
  23158. BABYLON.CircleEase = CircleEase;
  23159. var BackEase = (function (_super) {
  23160. __extends(BackEase, _super);
  23161. function BackEase(amplitude) {
  23162. if (amplitude === void 0) { amplitude = 1; }
  23163. _super.call(this);
  23164. this.amplitude = amplitude;
  23165. }
  23166. BackEase.prototype.easeInCore = function (gradient) {
  23167. var num = Math.max(0, this.amplitude);
  23168. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  23169. };
  23170. return BackEase;
  23171. })(EasingFunction);
  23172. BABYLON.BackEase = BackEase;
  23173. var BounceEase = (function (_super) {
  23174. __extends(BounceEase, _super);
  23175. function BounceEase(bounces, bounciness) {
  23176. if (bounces === void 0) { bounces = 3; }
  23177. if (bounciness === void 0) { bounciness = 2; }
  23178. _super.call(this);
  23179. this.bounces = bounces;
  23180. this.bounciness = bounciness;
  23181. }
  23182. BounceEase.prototype.easeInCore = function (gradient) {
  23183. var y = Math.max(0.0, this.bounces);
  23184. var bounciness = this.bounciness;
  23185. if (bounciness <= 1.0) {
  23186. bounciness = 1.001;
  23187. }
  23188. var num9 = Math.pow(bounciness, y);
  23189. var num5 = 1.0 - bounciness;
  23190. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  23191. var num15 = gradient * num4;
  23192. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  23193. var num3 = Math.floor(num65);
  23194. var num13 = num3 + 1.0;
  23195. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  23196. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  23197. var num7 = (num8 + num12) * 0.5;
  23198. var num6 = gradient - num7;
  23199. var num2 = num7 - num8;
  23200. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  23201. };
  23202. return BounceEase;
  23203. })(EasingFunction);
  23204. BABYLON.BounceEase = BounceEase;
  23205. var CubicEase = (function (_super) {
  23206. __extends(CubicEase, _super);
  23207. function CubicEase() {
  23208. _super.apply(this, arguments);
  23209. }
  23210. CubicEase.prototype.easeInCore = function (gradient) {
  23211. return (gradient * gradient * gradient);
  23212. };
  23213. return CubicEase;
  23214. })(EasingFunction);
  23215. BABYLON.CubicEase = CubicEase;
  23216. var ElasticEase = (function (_super) {
  23217. __extends(ElasticEase, _super);
  23218. function ElasticEase(oscillations, springiness) {
  23219. if (oscillations === void 0) { oscillations = 3; }
  23220. if (springiness === void 0) { springiness = 3; }
  23221. _super.call(this);
  23222. this.oscillations = oscillations;
  23223. this.springiness = springiness;
  23224. }
  23225. ElasticEase.prototype.easeInCore = function (gradient) {
  23226. var num2;
  23227. var num3 = Math.max(0.0, this.oscillations);
  23228. var num = Math.max(0.0, this.springiness);
  23229. if (num == 0) {
  23230. num2 = gradient;
  23231. }
  23232. else {
  23233. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  23234. }
  23235. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  23236. };
  23237. return ElasticEase;
  23238. })(EasingFunction);
  23239. BABYLON.ElasticEase = ElasticEase;
  23240. var ExponentialEase = (function (_super) {
  23241. __extends(ExponentialEase, _super);
  23242. function ExponentialEase(exponent) {
  23243. if (exponent === void 0) { exponent = 2; }
  23244. _super.call(this);
  23245. this.exponent = exponent;
  23246. }
  23247. ExponentialEase.prototype.easeInCore = function (gradient) {
  23248. if (this.exponent <= 0) {
  23249. return gradient;
  23250. }
  23251. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  23252. };
  23253. return ExponentialEase;
  23254. })(EasingFunction);
  23255. BABYLON.ExponentialEase = ExponentialEase;
  23256. var PowerEase = (function (_super) {
  23257. __extends(PowerEase, _super);
  23258. function PowerEase(power) {
  23259. if (power === void 0) { power = 2; }
  23260. _super.call(this);
  23261. this.power = power;
  23262. }
  23263. PowerEase.prototype.easeInCore = function (gradient) {
  23264. var y = Math.max(0.0, this.power);
  23265. return Math.pow(gradient, y);
  23266. };
  23267. return PowerEase;
  23268. })(EasingFunction);
  23269. BABYLON.PowerEase = PowerEase;
  23270. var QuadraticEase = (function (_super) {
  23271. __extends(QuadraticEase, _super);
  23272. function QuadraticEase() {
  23273. _super.apply(this, arguments);
  23274. }
  23275. QuadraticEase.prototype.easeInCore = function (gradient) {
  23276. return (gradient * gradient);
  23277. };
  23278. return QuadraticEase;
  23279. })(EasingFunction);
  23280. BABYLON.QuadraticEase = QuadraticEase;
  23281. var QuarticEase = (function (_super) {
  23282. __extends(QuarticEase, _super);
  23283. function QuarticEase() {
  23284. _super.apply(this, arguments);
  23285. }
  23286. QuarticEase.prototype.easeInCore = function (gradient) {
  23287. return (gradient * gradient * gradient * gradient);
  23288. };
  23289. return QuarticEase;
  23290. })(EasingFunction);
  23291. BABYLON.QuarticEase = QuarticEase;
  23292. var QuinticEase = (function (_super) {
  23293. __extends(QuinticEase, _super);
  23294. function QuinticEase() {
  23295. _super.apply(this, arguments);
  23296. }
  23297. QuinticEase.prototype.easeInCore = function (gradient) {
  23298. return (gradient * gradient * gradient * gradient * gradient);
  23299. };
  23300. return QuinticEase;
  23301. })(EasingFunction);
  23302. BABYLON.QuinticEase = QuinticEase;
  23303. var SineEase = (function (_super) {
  23304. __extends(SineEase, _super);
  23305. function SineEase() {
  23306. _super.apply(this, arguments);
  23307. }
  23308. SineEase.prototype.easeInCore = function (gradient) {
  23309. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  23310. };
  23311. return SineEase;
  23312. })(EasingFunction);
  23313. BABYLON.SineEase = SineEase;
  23314. var BezierCurveEase = (function (_super) {
  23315. __extends(BezierCurveEase, _super);
  23316. function BezierCurveEase(x1, y1, x2, y2) {
  23317. if (x1 === void 0) { x1 = 0; }
  23318. if (y1 === void 0) { y1 = 0; }
  23319. if (x2 === void 0) { x2 = 1; }
  23320. if (y2 === void 0) { y2 = 1; }
  23321. _super.call(this);
  23322. this.x1 = x1;
  23323. this.y1 = y1;
  23324. this.x2 = x2;
  23325. this.y2 = y2;
  23326. }
  23327. BezierCurveEase.prototype.easeInCore = function (gradient) {
  23328. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  23329. };
  23330. return BezierCurveEase;
  23331. })(EasingFunction);
  23332. BABYLON.BezierCurveEase = BezierCurveEase;
  23333. })(BABYLON || (BABYLON = {}));
  23334. var BABYLON;
  23335. (function (BABYLON) {
  23336. var Bone = (function (_super) {
  23337. __extends(Bone, _super);
  23338. function Bone(name, skeleton, parentBone, matrix, restPose) {
  23339. _super.call(this, name, skeleton.getScene());
  23340. this.name = name;
  23341. this.children = new Array();
  23342. this.animations = new Array();
  23343. this._worldTransform = new BABYLON.Matrix();
  23344. this._absoluteTransform = new BABYLON.Matrix();
  23345. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23346. this._skeleton = skeleton;
  23347. this._matrix = matrix;
  23348. this._baseMatrix = matrix;
  23349. this._restPose = restPose ? restPose : matrix.clone();
  23350. skeleton.bones.push(this);
  23351. if (parentBone) {
  23352. this._parent = parentBone;
  23353. parentBone.children.push(this);
  23354. }
  23355. else {
  23356. this._parent = null;
  23357. }
  23358. this._updateDifferenceMatrix();
  23359. }
  23360. // Members
  23361. Bone.prototype.getParent = function () {
  23362. return this._parent;
  23363. };
  23364. Bone.prototype.getLocalMatrix = function () {
  23365. return this._matrix;
  23366. };
  23367. Bone.prototype.getBaseMatrix = function () {
  23368. return this._baseMatrix;
  23369. };
  23370. Bone.prototype.getRestPose = function () {
  23371. return this._restPose;
  23372. };
  23373. Bone.prototype.returnToRest = function () {
  23374. this.updateMatrix(this._restPose.clone());
  23375. };
  23376. Bone.prototype.getWorldMatrix = function () {
  23377. return this._worldTransform;
  23378. };
  23379. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23380. return this._invertedAbsoluteTransform;
  23381. };
  23382. Bone.prototype.getAbsoluteTransform = function () {
  23383. return this._absoluteTransform;
  23384. };
  23385. // Methods
  23386. Bone.prototype.updateMatrix = function (matrix) {
  23387. this._baseMatrix = matrix.clone();
  23388. this._matrix = matrix.clone();
  23389. this._skeleton._markAsDirty();
  23390. this._updateDifferenceMatrix();
  23391. };
  23392. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  23393. if (!rootMatrix) {
  23394. rootMatrix = this._baseMatrix;
  23395. }
  23396. if (this._parent) {
  23397. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23398. }
  23399. else {
  23400. this._absoluteTransform.copyFrom(rootMatrix);
  23401. }
  23402. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23403. for (var index = 0; index < this.children.length; index++) {
  23404. this.children[index]._updateDifferenceMatrix();
  23405. }
  23406. };
  23407. Bone.prototype.markAsDirty = function () {
  23408. this._currentRenderId++;
  23409. this._skeleton._markAsDirty();
  23410. };
  23411. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23412. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23413. // all animation may be coming from a library skeleton, so may need to create animation
  23414. if (this.animations.length === 0) {
  23415. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23416. }
  23417. // get animation info / verify there is such a range from the source bone
  23418. var sourceRange = source.animations[0].getRange(rangeName);
  23419. if (!sourceRange) {
  23420. return false;
  23421. }
  23422. var from = sourceRange.from;
  23423. var to = sourceRange.to;
  23424. var sourceKeys = source.animations[0].getKeys();
  23425. // rescaling prep
  23426. var sourceBoneLength = source.length;
  23427. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23428. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23429. var destKeys = this.animations[0].getKeys();
  23430. // loop vars declaration / initialization
  23431. var orig;
  23432. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23433. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23434. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23435. var mat;
  23436. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23437. orig = sourceKeys[key];
  23438. if (orig.frame >= from && orig.frame <= to) {
  23439. if (scalingReqd) {
  23440. orig.value.decompose(origScale, origRotation, origTranslation);
  23441. origTranslation.scaleInPlace(ratio);
  23442. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23443. }
  23444. else {
  23445. mat = orig.value;
  23446. }
  23447. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23448. }
  23449. }
  23450. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23451. return true;
  23452. };
  23453. return Bone;
  23454. })(BABYLON.Node);
  23455. BABYLON.Bone = Bone;
  23456. })(BABYLON || (BABYLON = {}));
  23457. var BABYLON;
  23458. (function (BABYLON) {
  23459. var Skeleton = (function () {
  23460. function Skeleton(name, id, scene) {
  23461. this.name = name;
  23462. this.id = id;
  23463. this.bones = new Array();
  23464. this.needInitialSkinMatrix = false;
  23465. this._isDirty = true;
  23466. this._meshesWithPoseMatrix = new Array();
  23467. this._identity = BABYLON.Matrix.Identity();
  23468. this._ranges = {};
  23469. this.bones = [];
  23470. this._scene = scene;
  23471. scene.skeletons.push(this);
  23472. this.prepare();
  23473. //make sure it will recalculate the matrix next time prepare is called.
  23474. this._isDirty = true;
  23475. }
  23476. // Members
  23477. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23478. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23479. return mesh._bonesTransformMatrices;
  23480. }
  23481. return this._transformMatrices;
  23482. };
  23483. Skeleton.prototype.getScene = function () {
  23484. return this._scene;
  23485. };
  23486. // Methods
  23487. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23488. // check name not already in use
  23489. if (!this._ranges[name]) {
  23490. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23491. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23492. if (this.bones[i].animations[0]) {
  23493. this.bones[i].animations[0].createRange(name, from, to);
  23494. }
  23495. }
  23496. }
  23497. };
  23498. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23499. if (deleteFrames === void 0) { deleteFrames = true; }
  23500. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23501. if (this.bones[i].animations[0]) {
  23502. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23503. }
  23504. }
  23505. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23506. };
  23507. Skeleton.prototype.getAnimationRange = function (name) {
  23508. return this._ranges[name];
  23509. };
  23510. /**
  23511. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23512. */
  23513. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23514. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23515. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23516. return false;
  23517. }
  23518. var ret = true;
  23519. var frameOffset = this._getHighestAnimationFrame() + 1;
  23520. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23521. var boneDict = {};
  23522. var sourceBones = source.bones;
  23523. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23524. boneDict[sourceBones[i].name] = sourceBones[i];
  23525. }
  23526. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23527. var boneName = this.bones[i].name;
  23528. var sourceBone = boneDict[boneName];
  23529. if (sourceBone) {
  23530. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23531. }
  23532. else {
  23533. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23534. ret = false;
  23535. }
  23536. }
  23537. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23538. var range = source.getAnimationRange(name);
  23539. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23540. return ret;
  23541. };
  23542. Skeleton.prototype.returnToRest = function () {
  23543. for (var index = 0; index < this.bones.length; index++) {
  23544. this.bones[index].returnToRest();
  23545. }
  23546. };
  23547. Skeleton.prototype._getHighestAnimationFrame = function () {
  23548. var ret = 0;
  23549. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23550. if (this.bones[i].animations[0]) {
  23551. var highest = this.bones[i].animations[0].getHighestFrame();
  23552. if (ret < highest) {
  23553. ret = highest;
  23554. }
  23555. }
  23556. }
  23557. return ret;
  23558. };
  23559. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23560. var range = this.getAnimationRange(name);
  23561. if (!range) {
  23562. return null;
  23563. }
  23564. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23565. };
  23566. Skeleton.prototype._markAsDirty = function () {
  23567. this._isDirty = true;
  23568. };
  23569. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23570. this._meshesWithPoseMatrix.push(mesh);
  23571. };
  23572. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23573. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23574. if (index > -1) {
  23575. this._meshesWithPoseMatrix.splice(index, 1);
  23576. }
  23577. };
  23578. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23579. for (var index = 0; index < this.bones.length; index++) {
  23580. var bone = this.bones[index];
  23581. var parentBone = bone.getParent();
  23582. if (parentBone) {
  23583. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23584. }
  23585. else {
  23586. if (initialSkinMatrix) {
  23587. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23588. }
  23589. else {
  23590. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23591. }
  23592. }
  23593. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23594. }
  23595. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23596. };
  23597. Skeleton.prototype.prepare = function () {
  23598. if (!this._isDirty) {
  23599. return;
  23600. }
  23601. if (this.needInitialSkinMatrix) {
  23602. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23603. var mesh = this._meshesWithPoseMatrix[index];
  23604. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23605. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23606. }
  23607. var poseMatrix = mesh.getPoseMatrix();
  23608. // Prepare bones
  23609. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23610. var bone = this.bones[boneIndex];
  23611. if (!bone.getParent()) {
  23612. var matrix = bone.getBaseMatrix();
  23613. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23614. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23615. }
  23616. }
  23617. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23618. }
  23619. }
  23620. else {
  23621. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23622. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23623. }
  23624. this._computeTransformMatrices(this._transformMatrices, null);
  23625. }
  23626. this._isDirty = false;
  23627. this._scene._activeBones += this.bones.length;
  23628. };
  23629. Skeleton.prototype.getAnimatables = function () {
  23630. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23631. this._animatables = [];
  23632. for (var index = 0; index < this.bones.length; index++) {
  23633. this._animatables.push(this.bones[index]);
  23634. }
  23635. }
  23636. return this._animatables;
  23637. };
  23638. Skeleton.prototype.clone = function (name, id) {
  23639. var result = new Skeleton(name, id || name, this._scene);
  23640. for (var index = 0; index < this.bones.length; index++) {
  23641. var source = this.bones[index];
  23642. var parentBone = null;
  23643. if (source.getParent()) {
  23644. var parentIndex = this.bones.indexOf(source.getParent());
  23645. parentBone = result.bones[parentIndex];
  23646. }
  23647. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23648. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23649. }
  23650. return result;
  23651. };
  23652. Skeleton.prototype.dispose = function () {
  23653. this._meshesWithPoseMatrix = [];
  23654. // Animations
  23655. this.getScene().stopAnimation(this);
  23656. // Remove from scene
  23657. this.getScene().removeSkeleton(this);
  23658. };
  23659. Skeleton.prototype.serialize = function () {
  23660. var serializationObject = {};
  23661. serializationObject.name = this.name;
  23662. serializationObject.id = this.id;
  23663. serializationObject.bones = [];
  23664. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23665. for (var index = 0; index < this.bones.length; index++) {
  23666. var bone = this.bones[index];
  23667. var serializedBone = {
  23668. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23669. name: bone.name,
  23670. matrix: bone.getLocalMatrix().toArray(),
  23671. rest: bone.getRestPose().toArray()
  23672. };
  23673. serializationObject.bones.push(serializedBone);
  23674. if (bone.length) {
  23675. serializedBone.length = bone.length;
  23676. }
  23677. if (bone.animations && bone.animations.length > 0) {
  23678. serializedBone.animation = bone.animations[0].serialize();
  23679. }
  23680. serializationObject.ranges = [];
  23681. for (var name in this._ranges) {
  23682. var range = {};
  23683. range.name = name;
  23684. range.from = this._ranges[name].from;
  23685. range.to = this._ranges[name].to;
  23686. serializationObject.ranges.push(range);
  23687. }
  23688. }
  23689. return serializationObject;
  23690. };
  23691. Skeleton.Parse = function (parsedSkeleton, scene) {
  23692. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23693. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23694. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23695. var parsedBone = parsedSkeleton.bones[index];
  23696. var parentBone = null;
  23697. if (parsedBone.parentBoneIndex > -1) {
  23698. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23699. }
  23700. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23701. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23702. if (parsedBone.length) {
  23703. bone.length = parsedBone.length;
  23704. }
  23705. if (parsedBone.animation) {
  23706. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23707. }
  23708. }
  23709. // placed after bones, so createAnimationRange can cascade down
  23710. if (parsedSkeleton.ranges) {
  23711. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23712. var data = parsedSkeleton.ranges[index];
  23713. skeleton.createAnimationRange(data.name, data.from, data.to);
  23714. }
  23715. }
  23716. return skeleton;
  23717. };
  23718. return Skeleton;
  23719. })();
  23720. BABYLON.Skeleton = Skeleton;
  23721. })(BABYLON || (BABYLON = {}));
  23722. var BABYLON;
  23723. (function (BABYLON) {
  23724. var PostProcess = (function () {
  23725. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23726. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23727. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23728. this.name = name;
  23729. this.width = -1;
  23730. this.height = -1;
  23731. this._reusable = false;
  23732. this._textures = new BABYLON.SmartArray(2);
  23733. this._currentRenderTextureInd = 0;
  23734. if (camera != null) {
  23735. this._camera = camera;
  23736. this._scene = camera.getScene();
  23737. camera.attachPostProcess(this);
  23738. this._engine = this._scene.getEngine();
  23739. }
  23740. else {
  23741. this._engine = engine;
  23742. }
  23743. this._renderRatio = ratio;
  23744. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23745. this._reusable = reusable || false;
  23746. this._textureType = textureType;
  23747. this._samplers = samplers || [];
  23748. this._samplers.push("textureSampler");
  23749. this._fragmentUrl = fragmentUrl;
  23750. this._parameters = parameters || [];
  23751. this.updateEffect(defines);
  23752. }
  23753. PostProcess.prototype.updateEffect = function (defines) {
  23754. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23755. };
  23756. PostProcess.prototype.isReusable = function () {
  23757. return this._reusable;
  23758. };
  23759. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23760. camera = camera || this._camera;
  23761. var scene = camera.getScene();
  23762. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23763. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23764. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23765. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23766. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23767. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23768. if (this._textures.length > 0) {
  23769. for (var i = 0; i < this._textures.length; i++) {
  23770. this._engine._releaseTexture(this._textures.data[i]);
  23771. }
  23772. this._textures.reset();
  23773. }
  23774. this.width = desiredWidth;
  23775. this.height = desiredHeight;
  23776. 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 }));
  23777. if (this._reusable) {
  23778. 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 }));
  23779. }
  23780. if (this.onSizeChanged) {
  23781. this.onSizeChanged();
  23782. }
  23783. }
  23784. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23785. if (this.onActivate) {
  23786. this.onActivate(camera);
  23787. }
  23788. // Clear
  23789. if (this.clearColor) {
  23790. this._engine.clear(this.clearColor, true, true);
  23791. }
  23792. else {
  23793. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23794. }
  23795. if (this._reusable) {
  23796. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23797. }
  23798. };
  23799. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23800. get: function () {
  23801. return this._effect.isSupported;
  23802. },
  23803. enumerable: true,
  23804. configurable: true
  23805. });
  23806. PostProcess.prototype.apply = function () {
  23807. // Check
  23808. if (!this._effect.isReady())
  23809. return null;
  23810. // States
  23811. this._engine.enableEffect(this._effect);
  23812. this._engine.setState(false);
  23813. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23814. this._engine.setDepthBuffer(false);
  23815. this._engine.setDepthWrite(false);
  23816. // Texture
  23817. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23818. // Parameters
  23819. if (this.onApply) {
  23820. this.onApply(this._effect);
  23821. }
  23822. return this._effect;
  23823. };
  23824. PostProcess.prototype.dispose = function (camera) {
  23825. camera = camera || this._camera;
  23826. if (this._textures.length > 0) {
  23827. for (var i = 0; i < this._textures.length; i++) {
  23828. this._engine._releaseTexture(this._textures.data[i]);
  23829. }
  23830. this._textures.reset();
  23831. }
  23832. if (!camera) {
  23833. return;
  23834. }
  23835. camera.detachPostProcess(this);
  23836. var index = camera._postProcesses.indexOf(this);
  23837. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23838. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23839. }
  23840. };
  23841. return PostProcess;
  23842. })();
  23843. BABYLON.PostProcess = PostProcess;
  23844. })(BABYLON || (BABYLON = {}));
  23845. var BABYLON;
  23846. (function (BABYLON) {
  23847. var PostProcessManager = (function () {
  23848. function PostProcessManager(scene) {
  23849. this._vertexDeclaration = [2];
  23850. this._vertexStrideSize = 2 * 4;
  23851. this._scene = scene;
  23852. }
  23853. PostProcessManager.prototype._prepareBuffers = function () {
  23854. if (this._vertexBuffer) {
  23855. return;
  23856. }
  23857. // VBO
  23858. var vertices = [];
  23859. vertices.push(1, 1);
  23860. vertices.push(-1, 1);
  23861. vertices.push(-1, -1);
  23862. vertices.push(1, -1);
  23863. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23864. // Indices
  23865. var indices = [];
  23866. indices.push(0);
  23867. indices.push(1);
  23868. indices.push(2);
  23869. indices.push(0);
  23870. indices.push(2);
  23871. indices.push(3);
  23872. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23873. };
  23874. // Methods
  23875. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23876. var postProcesses = this._scene.activeCamera._postProcesses;
  23877. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23878. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23879. return false;
  23880. }
  23881. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23882. return true;
  23883. };
  23884. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23885. var engine = this._scene.getEngine();
  23886. for (var index = 0; index < postProcesses.length; index++) {
  23887. if (index < postProcesses.length - 1) {
  23888. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23889. }
  23890. else {
  23891. if (targetTexture) {
  23892. engine.bindFramebuffer(targetTexture);
  23893. }
  23894. else {
  23895. engine.restoreDefaultFramebuffer();
  23896. }
  23897. }
  23898. var pp = postProcesses[index];
  23899. var effect = pp.apply();
  23900. if (effect) {
  23901. if (pp.onBeforeRender) {
  23902. pp.onBeforeRender(effect);
  23903. }
  23904. // VBOs
  23905. this._prepareBuffers();
  23906. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23907. // Draw order
  23908. engine.draw(true, 0, 6);
  23909. if (pp.onAfterRender) {
  23910. pp.onAfterRender(effect);
  23911. }
  23912. }
  23913. }
  23914. // Restore depth buffer
  23915. engine.setDepthBuffer(true);
  23916. engine.setDepthWrite(true);
  23917. };
  23918. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23919. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23920. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23921. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23922. return;
  23923. }
  23924. var engine = this._scene.getEngine();
  23925. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23926. if (index < postProcessesTakenIndices.length - 1) {
  23927. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23928. }
  23929. else {
  23930. if (targetTexture) {
  23931. engine.bindFramebuffer(targetTexture, faceIndex);
  23932. }
  23933. else {
  23934. engine.restoreDefaultFramebuffer();
  23935. }
  23936. }
  23937. if (doNotPresent) {
  23938. break;
  23939. }
  23940. var pp = postProcesses[postProcessesTakenIndices[index]];
  23941. var effect = pp.apply();
  23942. if (effect) {
  23943. if (pp.onBeforeRender) {
  23944. pp.onBeforeRender(effect);
  23945. }
  23946. // VBOs
  23947. this._prepareBuffers();
  23948. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23949. // Draw order
  23950. engine.draw(true, 0, 6);
  23951. if (pp.onAfterRender) {
  23952. pp.onAfterRender(effect);
  23953. }
  23954. }
  23955. }
  23956. // Restore depth buffer
  23957. engine.setDepthBuffer(true);
  23958. engine.setDepthWrite(true);
  23959. };
  23960. PostProcessManager.prototype.dispose = function () {
  23961. if (this._vertexBuffer) {
  23962. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23963. this._vertexBuffer = null;
  23964. }
  23965. if (this._indexBuffer) {
  23966. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23967. this._indexBuffer = null;
  23968. }
  23969. };
  23970. return PostProcessManager;
  23971. })();
  23972. BABYLON.PostProcessManager = PostProcessManager;
  23973. })(BABYLON || (BABYLON = {}));
  23974. var BABYLON;
  23975. (function (BABYLON) {
  23976. var PassPostProcess = (function (_super) {
  23977. __extends(PassPostProcess, _super);
  23978. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23979. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23980. }
  23981. return PassPostProcess;
  23982. })(BABYLON.PostProcess);
  23983. BABYLON.PassPostProcess = PassPostProcess;
  23984. })(BABYLON || (BABYLON = {}));
  23985. var BABYLON;
  23986. (function (BABYLON) {
  23987. var PhysicsJoint = (function () {
  23988. function PhysicsJoint(type, jointData) {
  23989. this.type = type;
  23990. this.jointData = jointData;
  23991. jointData.nativeParams = jointData.nativeParams || {};
  23992. }
  23993. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  23994. get: function () {
  23995. return this._physicsJoint;
  23996. },
  23997. set: function (newJoint) {
  23998. if (this._physicsJoint) {
  23999. }
  24000. this._physicsJoint = newJoint;
  24001. },
  24002. enumerable: true,
  24003. configurable: true
  24004. });
  24005. //TODO check if the native joints are the same
  24006. //Joint Types
  24007. PhysicsJoint.DistanceJoint = 0;
  24008. PhysicsJoint.HingeJoint = 1;
  24009. PhysicsJoint.BallAndSocketJoint = 2;
  24010. PhysicsJoint.WheelJoint = 3;
  24011. PhysicsJoint.SliderJoint = 4;
  24012. //OIMO
  24013. PhysicsJoint.PrismaticJoint = 5;
  24014. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  24015. PhysicsJoint.UniversalJoint = 6;
  24016. PhysicsJoint.Hinge2Joint = 7;
  24017. //Cannon
  24018. //Similar to a Ball-Joint. Different in params
  24019. //TODO check!!
  24020. PhysicsJoint.PointToPointJoint = 8;
  24021. //Cannon only at the moment
  24022. PhysicsJoint.SpringJoint = 9;
  24023. return PhysicsJoint;
  24024. })();
  24025. BABYLON.PhysicsJoint = PhysicsJoint;
  24026. })(BABYLON || (BABYLON = {}));
  24027. var BABYLON;
  24028. (function (BABYLON) {
  24029. var PhysicsImpostor = (function () {
  24030. function PhysicsImpostor(_mesh, type, _options) {
  24031. var _this = this;
  24032. if (_options === void 0) { _options = { mass: 0 }; }
  24033. this._mesh = _mesh;
  24034. this.type = type;
  24035. this._options = _options;
  24036. this._bodyUpdateRequired = false;
  24037. this._onBeforePhysicsStepCallbacks = new Array();
  24038. this._onAfterPhysicsStepCallbacks = new Array();
  24039. this._onPhysicsCollideCallbacks = [];
  24040. this._deltaPosition = BABYLON.Vector3.Zero();
  24041. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  24042. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  24043. /**
  24044. * this function is executed by the physics engine.
  24045. */
  24046. this.beforeStep = function () {
  24047. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  24048. //conjugate deltaRotation
  24049. if (_this._deltaRotationConjugated) {
  24050. _this.mesh.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  24051. }
  24052. else {
  24053. _this._tmpRotationWithDelta.copyFrom(_this.mesh.rotationQuaternion);
  24054. }
  24055. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  24056. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  24057. func(_this);
  24058. });
  24059. };
  24060. /**
  24061. * this function is executed by the physics engine.
  24062. */
  24063. this.afterStep = function () {
  24064. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  24065. func(_this);
  24066. });
  24067. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  24068. _this.mesh.position.addInPlace(_this._deltaPosition);
  24069. if (_this._deltaRotation) {
  24070. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  24071. }
  24072. };
  24073. //event and body object due to cannon's event-based architecture.
  24074. this.onCollide = function (e) {
  24075. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  24076. if (otherImpostor) {
  24077. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  24078. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  24079. }).forEach(function (obj) {
  24080. obj.callback(_this, otherImpostor);
  24081. });
  24082. }
  24083. };
  24084. //default options params
  24085. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  24086. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  24087. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  24088. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  24089. this._joints = [];
  24090. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  24091. if (!this._mesh.parent) {
  24092. this._init();
  24093. }
  24094. }
  24095. /**
  24096. * This function will completly initialize this impostor.
  24097. * It will create a new body - but only if this mesh has no parent.
  24098. * If it has, this impostor will not be used other than to define the impostor
  24099. * of the child mesh.
  24100. */
  24101. PhysicsImpostor.prototype._init = function () {
  24102. this._physicsEngine.removeImpostor(this);
  24103. this.physicsBody = null;
  24104. this._parent = this._parent || this._getPhysicsParent();
  24105. if (!this.parent) {
  24106. this._physicsEngine.addImpostor(this);
  24107. }
  24108. };
  24109. PhysicsImpostor.prototype._getPhysicsParent = function () {
  24110. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  24111. var parentMesh = this.mesh.parent;
  24112. return parentMesh.getPhysicsImpostor();
  24113. }
  24114. return;
  24115. };
  24116. /**
  24117. * Should a new body be generated.
  24118. */
  24119. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  24120. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  24121. };
  24122. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  24123. this.forceUpdate();
  24124. };
  24125. /**
  24126. * Force a regeneration of this or the parent's impostor's body.
  24127. * Use under cautious - This will remove all joints already implemented.
  24128. */
  24129. PhysicsImpostor.prototype.forceUpdate = function () {
  24130. this._init();
  24131. if (this.parent) {
  24132. this.parent.forceUpdate();
  24133. }
  24134. };
  24135. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  24136. get: function () {
  24137. return this._mesh;
  24138. },
  24139. enumerable: true,
  24140. configurable: true
  24141. });
  24142. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  24143. /**
  24144. * Gets the body that holds this impostor. Either its own, or its parent.
  24145. */
  24146. get: function () {
  24147. return this._parent ? this._parent.physicsBody : this._physicsBody;
  24148. },
  24149. /**
  24150. * Set the physics body. Used mainly by the physics engine/plugin
  24151. */
  24152. set: function (physicsBody) {
  24153. if (this._physicsBody) {
  24154. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  24155. }
  24156. this._physicsBody = physicsBody;
  24157. this.resetUpdateFlags();
  24158. },
  24159. enumerable: true,
  24160. configurable: true
  24161. });
  24162. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  24163. get: function () {
  24164. return this._parent;
  24165. },
  24166. enumerable: true,
  24167. configurable: true
  24168. });
  24169. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  24170. this._bodyUpdateRequired = false;
  24171. };
  24172. /**
  24173. * Get a specific parametes from the options parameter.
  24174. */
  24175. PhysicsImpostor.prototype.getParam = function (paramName) {
  24176. return this._options[paramName];
  24177. };
  24178. /**
  24179. * Sets a specific parameter in the options given to the physics plugin
  24180. */
  24181. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  24182. this._options[paramName] = value;
  24183. this._bodyUpdateRequired = true;
  24184. };
  24185. /**
  24186. * Set the body's velocity.
  24187. */
  24188. PhysicsImpostor.prototype.setVelocity = function (velocity) {
  24189. this._physicsEngine.getPhysicsPlugin().setVelocity(this, velocity);
  24190. };
  24191. /**
  24192. * Execute a function with the physics plugin native code.
  24193. * Provide a function the will have two variables - the world object and the physics body object.
  24194. */
  24195. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  24196. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  24197. };
  24198. /**
  24199. * Register a function that will be executed before the physics world is stepping forward.
  24200. */
  24201. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  24202. this._onBeforePhysicsStepCallbacks.push(func);
  24203. };
  24204. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  24205. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  24206. if (index > -1) {
  24207. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  24208. }
  24209. else {
  24210. BABYLON.Tools.Warn("Function to remove was not found");
  24211. }
  24212. };
  24213. /**
  24214. * Register a function that will be executed after the physics step
  24215. */
  24216. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  24217. this._onAfterPhysicsStepCallbacks.push(func);
  24218. };
  24219. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  24220. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  24221. if (index > -1) {
  24222. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  24223. }
  24224. else {
  24225. BABYLON.Tools.Warn("Function to remove was not found");
  24226. }
  24227. };
  24228. /**
  24229. * register a function that will be executed when this impostor collides against a different body.
  24230. */
  24231. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  24232. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  24233. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  24234. };
  24235. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  24236. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  24237. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  24238. if (index > -1) {
  24239. this._onPhysicsCollideCallbacks.splice(index, 1);
  24240. }
  24241. else {
  24242. BABYLON.Tools.Warn("Function to remove was not found");
  24243. }
  24244. };
  24245. /**
  24246. * Apply a force
  24247. */
  24248. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  24249. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  24250. };
  24251. /**
  24252. * Apply an impulse
  24253. */
  24254. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  24255. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  24256. };
  24257. /**
  24258. * A help function to create a joint.
  24259. */
  24260. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  24261. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  24262. this.addJoint(otherImpostor, joint);
  24263. };
  24264. /**
  24265. * Add a joint to this impostor with a different impostor.
  24266. */
  24267. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  24268. this._joints.push({
  24269. otherImpostor: otherImpostor,
  24270. joint: joint
  24271. });
  24272. this._physicsEngine.addJoint(this, otherImpostor, joint);
  24273. };
  24274. /**
  24275. * Will keep this body still, in a sleep mode.
  24276. */
  24277. PhysicsImpostor.prototype.sleep = function () {
  24278. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  24279. };
  24280. /**
  24281. * Wake the body up.
  24282. */
  24283. PhysicsImpostor.prototype.wakeUp = function () {
  24284. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  24285. };
  24286. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  24287. if (disposeChildren === void 0) { disposeChildren = true; }
  24288. this.physicsBody = null;
  24289. if (this.parent) {
  24290. this.parent.forceUpdate();
  24291. }
  24292. else {
  24293. this.mesh.getChildMeshes().forEach(function (mesh) {
  24294. if (mesh.physicsImpostor) {
  24295. if (disposeChildren) {
  24296. mesh.physicsImpostor.dispose();
  24297. mesh.physicsImpostor = null;
  24298. }
  24299. }
  24300. });
  24301. }
  24302. };
  24303. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  24304. this._deltaPosition.copyFrom(position);
  24305. };
  24306. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  24307. if (!this._deltaRotation) {
  24308. this._deltaRotation = new BABYLON.Quaternion();
  24309. }
  24310. this._deltaRotation.copyFrom(rotation);
  24311. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  24312. };
  24313. //Impostor types
  24314. PhysicsImpostor.NoImpostor = 0;
  24315. PhysicsImpostor.SphereImpostor = 1;
  24316. PhysicsImpostor.BoxImpostor = 2;
  24317. PhysicsImpostor.PlaneImpostor = 3;
  24318. PhysicsImpostor.MeshImpostor = 4;
  24319. PhysicsImpostor.CapsuleImpostor = 5;
  24320. PhysicsImpostor.ConeImpostor = 6;
  24321. PhysicsImpostor.CylinderImpostor = 7;
  24322. PhysicsImpostor.ConvexHullImpostor = 8;
  24323. PhysicsImpostor.HeightmapImpostor = 9;
  24324. return PhysicsImpostor;
  24325. })();
  24326. BABYLON.PhysicsImpostor = PhysicsImpostor;
  24327. })(BABYLON || (BABYLON = {}));
  24328. var BABYLON;
  24329. (function (BABYLON) {
  24330. var PhysicsEngine = (function () {
  24331. function PhysicsEngine(gravity, _physicsPlugin) {
  24332. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  24333. this._physicsPlugin = _physicsPlugin;
  24334. //new methods and parameters
  24335. this._impostors = [];
  24336. this._joints = [];
  24337. if (!this._physicsPlugin.isSupported()) {
  24338. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  24339. + "Please make sure it is included.");
  24340. }
  24341. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24342. this.setGravity(gravity);
  24343. }
  24344. PhysicsEngine.prototype.setGravity = function (gravity) {
  24345. this.gravity = gravity;
  24346. this._physicsPlugin.setGravity(this.gravity);
  24347. };
  24348. PhysicsEngine.prototype.dispose = function () {
  24349. this._impostors.forEach(function (impostor) {
  24350. impostor.dispose();
  24351. });
  24352. this._physicsPlugin.dispose();
  24353. };
  24354. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  24355. return this._physicsPlugin.name;
  24356. };
  24357. PhysicsEngine.prototype.addImpostor = function (impostor) {
  24358. this._impostors.push(impostor);
  24359. //if no parent, generate the body
  24360. if (!impostor.parent) {
  24361. this._physicsPlugin.generatePhysicsBody(impostor);
  24362. }
  24363. };
  24364. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  24365. var index = this._impostors.indexOf(impostor);
  24366. if (index > -1) {
  24367. var removed = this._impostors.splice(index, 1);
  24368. //Is it needed?
  24369. if (removed.length) {
  24370. //this will also remove it from the world.
  24371. removed[0].physicsBody = null;
  24372. }
  24373. }
  24374. };
  24375. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  24376. var impostorJoint = {
  24377. mainImpostor: mainImpostor,
  24378. connectedImpostor: connectedImpostor,
  24379. joint: joint
  24380. };
  24381. this._joints.push(impostorJoint);
  24382. this._physicsPlugin.generateJoint(impostorJoint);
  24383. };
  24384. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  24385. var matchingJoints = this._joints.filter(function (impostorJoint) {
  24386. return (impostorJoint.connectedImpostor === connectedImpostor
  24387. && impostorJoint.joint === joint
  24388. && impostorJoint.mainImpostor === mainImpostor);
  24389. });
  24390. if (matchingJoints.length) {
  24391. this._physicsPlugin.removeJoint(matchingJoints[0]);
  24392. }
  24393. };
  24394. /**
  24395. * Called by the scene. no need to call it.
  24396. */
  24397. PhysicsEngine.prototype._step = function (delta) {
  24398. var _this = this;
  24399. //check if any mesh has no body / requires an update
  24400. this._impostors.forEach(function (impostor) {
  24401. if (impostor.isBodyInitRequired()) {
  24402. _this._physicsPlugin.generatePhysicsBody(impostor);
  24403. }
  24404. });
  24405. if (delta > 0.1) {
  24406. delta = 0.1;
  24407. }
  24408. else if (delta <= 0) {
  24409. delta = 1.0 / 60.0;
  24410. }
  24411. this._physicsPlugin.executeStep(delta, this._impostors);
  24412. };
  24413. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  24414. return this._physicsPlugin;
  24415. };
  24416. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  24417. for (var i = 0; i < this._impostors.length; ++i) {
  24418. if (this._impostors[i].physicsBody === body) {
  24419. return this._impostors[i];
  24420. }
  24421. }
  24422. };
  24423. // Statics, Legacy support.
  24424. /**
  24425. * @Deprecated
  24426. *
  24427. */
  24428. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  24429. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  24430. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  24431. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  24432. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  24433. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  24434. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  24435. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  24436. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  24437. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  24438. PhysicsEngine.Epsilon = 0.001;
  24439. return PhysicsEngine;
  24440. })();
  24441. BABYLON.PhysicsEngine = PhysicsEngine;
  24442. })(BABYLON || (BABYLON = {}));
  24443. var BABYLON;
  24444. (function (BABYLON) {
  24445. var VertexData = (function () {
  24446. function VertexData() {
  24447. }
  24448. VertexData.prototype.set = function (data, kind) {
  24449. switch (kind) {
  24450. case BABYLON.VertexBuffer.PositionKind:
  24451. this.positions = data;
  24452. break;
  24453. case BABYLON.VertexBuffer.NormalKind:
  24454. this.normals = data;
  24455. break;
  24456. case BABYLON.VertexBuffer.UVKind:
  24457. this.uvs = data;
  24458. break;
  24459. case BABYLON.VertexBuffer.UV2Kind:
  24460. this.uvs2 = data;
  24461. break;
  24462. case BABYLON.VertexBuffer.UV3Kind:
  24463. this.uvs3 = data;
  24464. break;
  24465. case BABYLON.VertexBuffer.UV4Kind:
  24466. this.uvs4 = data;
  24467. break;
  24468. case BABYLON.VertexBuffer.UV5Kind:
  24469. this.uvs5 = data;
  24470. break;
  24471. case BABYLON.VertexBuffer.UV6Kind:
  24472. this.uvs6 = data;
  24473. break;
  24474. case BABYLON.VertexBuffer.ColorKind:
  24475. this.colors = data;
  24476. break;
  24477. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24478. this.matricesIndices = data;
  24479. break;
  24480. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24481. this.matricesWeights = data;
  24482. break;
  24483. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24484. this.matricesIndicesExtra = data;
  24485. break;
  24486. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24487. this.matricesWeightsExtra = data;
  24488. break;
  24489. }
  24490. };
  24491. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24492. this._applyTo(mesh, updatable);
  24493. };
  24494. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24495. this._applyTo(geometry, updatable);
  24496. };
  24497. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24498. this._update(mesh);
  24499. };
  24500. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24501. this._update(geometry);
  24502. };
  24503. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24504. if (this.positions) {
  24505. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24506. }
  24507. if (this.normals) {
  24508. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24509. }
  24510. if (this.uvs) {
  24511. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24512. }
  24513. if (this.uvs2) {
  24514. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24515. }
  24516. if (this.uvs3) {
  24517. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24518. }
  24519. if (this.uvs4) {
  24520. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24521. }
  24522. if (this.uvs5) {
  24523. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24524. }
  24525. if (this.uvs6) {
  24526. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24527. }
  24528. if (this.colors) {
  24529. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24530. }
  24531. if (this.matricesIndices) {
  24532. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24533. }
  24534. if (this.matricesWeights) {
  24535. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24536. }
  24537. if (this.matricesIndicesExtra) {
  24538. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24539. }
  24540. if (this.matricesWeightsExtra) {
  24541. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24542. }
  24543. if (this.indices) {
  24544. meshOrGeometry.setIndices(this.indices);
  24545. }
  24546. };
  24547. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24548. if (this.positions) {
  24549. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24550. }
  24551. if (this.normals) {
  24552. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24553. }
  24554. if (this.uvs) {
  24555. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24556. }
  24557. if (this.uvs2) {
  24558. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24559. }
  24560. if (this.uvs3) {
  24561. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24562. }
  24563. if (this.uvs4) {
  24564. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24565. }
  24566. if (this.uvs5) {
  24567. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24568. }
  24569. if (this.uvs6) {
  24570. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24571. }
  24572. if (this.colors) {
  24573. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24574. }
  24575. if (this.matricesIndices) {
  24576. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24577. }
  24578. if (this.matricesWeights) {
  24579. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24580. }
  24581. if (this.matricesIndicesExtra) {
  24582. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24583. }
  24584. if (this.matricesWeightsExtra) {
  24585. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24586. }
  24587. if (this.indices) {
  24588. meshOrGeometry.setIndices(this.indices);
  24589. }
  24590. };
  24591. VertexData.prototype.transform = function (matrix) {
  24592. var transformed = BABYLON.Vector3.Zero();
  24593. var index;
  24594. if (this.positions) {
  24595. var position = BABYLON.Vector3.Zero();
  24596. for (index = 0; index < this.positions.length; index += 3) {
  24597. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24598. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24599. this.positions[index] = transformed.x;
  24600. this.positions[index + 1] = transformed.y;
  24601. this.positions[index + 2] = transformed.z;
  24602. }
  24603. }
  24604. if (this.normals) {
  24605. var normal = BABYLON.Vector3.Zero();
  24606. for (index = 0; index < this.normals.length; index += 3) {
  24607. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24608. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24609. this.normals[index] = transformed.x;
  24610. this.normals[index + 1] = transformed.y;
  24611. this.normals[index + 2] = transformed.z;
  24612. }
  24613. }
  24614. };
  24615. VertexData.prototype.merge = function (other) {
  24616. if (other.indices) {
  24617. if (!this.indices) {
  24618. this.indices = [];
  24619. }
  24620. var offset = this.positions ? this.positions.length / 3 : 0;
  24621. for (var index = 0; index < other.indices.length; index++) {
  24622. //TODO check type - if Int32Array!
  24623. this.indices.push(other.indices[index] + offset);
  24624. }
  24625. }
  24626. this.positions = this._mergeElement(this.positions, other.positions);
  24627. this.normals = this._mergeElement(this.normals, other.normals);
  24628. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24629. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24630. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24631. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24632. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24633. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24634. this.colors = this._mergeElement(this.colors, other.colors);
  24635. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24636. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24637. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24638. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24639. };
  24640. VertexData.prototype._mergeElement = function (source, other) {
  24641. if (!other)
  24642. return source;
  24643. if (!source)
  24644. return other;
  24645. var len = other.length + source.length;
  24646. var isSrcTypedArray = source instanceof Float32Array;
  24647. var isOthTypedArray = other instanceof Float32Array;
  24648. // use non-loop method when the source is Float32Array
  24649. if (isSrcTypedArray) {
  24650. var ret32 = new Float32Array(len);
  24651. ret32.set(source);
  24652. ret32.set(other, source.length);
  24653. return ret32;
  24654. }
  24655. else if (!isOthTypedArray) {
  24656. return source.concat(other);
  24657. }
  24658. else {
  24659. var ret = source.slice(0); // copy source to a separate array
  24660. for (var i = 0, len = other.length; i < len; i++) {
  24661. ret.push(other[i]);
  24662. }
  24663. return ret;
  24664. }
  24665. };
  24666. VertexData.prototype.serialize = function () {
  24667. var serializationObject = this.serialize();
  24668. if (this.positions) {
  24669. serializationObject.positions = this.positions;
  24670. }
  24671. if (this.normals) {
  24672. serializationObject.normals = this.normals;
  24673. }
  24674. if (this.uvs) {
  24675. serializationObject.uvs = this.uvs;
  24676. }
  24677. if (this.uvs2) {
  24678. serializationObject.uvs2 = this.uvs2;
  24679. }
  24680. if (this.uvs3) {
  24681. serializationObject.uvs3 = this.uvs3;
  24682. }
  24683. if (this.uvs4) {
  24684. serializationObject.uvs4 = this.uvs4;
  24685. }
  24686. if (this.uvs5) {
  24687. serializationObject.uvs5 = this.uvs5;
  24688. }
  24689. if (this.uvs6) {
  24690. serializationObject.uvs6 = this.uvs6;
  24691. }
  24692. if (this.colors) {
  24693. serializationObject.colors = this.colors;
  24694. }
  24695. if (this.matricesIndices) {
  24696. serializationObject.matricesIndices = this.matricesIndices;
  24697. serializationObject.matricesIndices._isExpanded = true;
  24698. }
  24699. if (this.matricesWeights) {
  24700. serializationObject.matricesWeights = this.matricesWeights;
  24701. }
  24702. if (this.matricesIndicesExtra) {
  24703. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24704. serializationObject.matricesIndicesExtra._isExpanded = true;
  24705. }
  24706. if (this.matricesWeightsExtra) {
  24707. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24708. }
  24709. serializationObject.indices = this.indices;
  24710. return serializationObject;
  24711. };
  24712. // Statics
  24713. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24714. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24715. };
  24716. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24717. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24718. };
  24719. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24720. var result = new VertexData();
  24721. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24722. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24723. }
  24724. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24725. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24726. }
  24727. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24728. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24729. }
  24730. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24731. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24732. }
  24733. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24734. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  24735. }
  24736. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24737. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  24738. }
  24739. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24740. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  24741. }
  24742. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24743. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24744. }
  24745. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24746. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24747. }
  24748. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24749. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24750. }
  24751. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24752. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24753. }
  24754. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24755. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24756. }
  24757. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24758. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24759. }
  24760. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24761. return result;
  24762. };
  24763. VertexData.CreateRibbon = function (options) {
  24764. var pathArray = options.pathArray;
  24765. var closeArray = options.closeArray || false;
  24766. var closePath = options.closePath || false;
  24767. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24768. var offset = options.offset || defaultOffset;
  24769. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24770. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24771. var positions = [];
  24772. var indices = [];
  24773. var normals = [];
  24774. var uvs = [];
  24775. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24776. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24777. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24778. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24779. var minlg; // minimal length among all paths from pathArray
  24780. var lg = []; // array of path lengths : nb of vertex per path
  24781. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24782. var p; // path iterator
  24783. var i; // point iterator
  24784. var j; // point iterator
  24785. // if single path in pathArray
  24786. if (pathArray.length < 2) {
  24787. var ar1 = [];
  24788. var ar2 = [];
  24789. for (i = 0; i < pathArray[0].length - offset; i++) {
  24790. ar1.push(pathArray[0][i]);
  24791. ar2.push(pathArray[0][i + offset]);
  24792. }
  24793. pathArray = [ar1, ar2];
  24794. }
  24795. // positions and horizontal distances (u)
  24796. var idc = 0;
  24797. var closePathCorr = (closePath) ? 1 : 0;
  24798. var path;
  24799. var l;
  24800. minlg = pathArray[0].length;
  24801. var vectlg;
  24802. var dist;
  24803. for (p = 0; p < pathArray.length; p++) {
  24804. uTotalDistance[p] = 0;
  24805. us[p] = [0];
  24806. path = pathArray[p];
  24807. l = path.length;
  24808. minlg = (minlg < l) ? minlg : l;
  24809. j = 0;
  24810. while (j < l) {
  24811. positions.push(path[j].x, path[j].y, path[j].z);
  24812. if (j > 0) {
  24813. vectlg = path[j].subtract(path[j - 1]).length();
  24814. dist = vectlg + uTotalDistance[p];
  24815. us[p].push(dist);
  24816. uTotalDistance[p] = dist;
  24817. }
  24818. j++;
  24819. }
  24820. if (closePath) {
  24821. j--;
  24822. positions.push(path[0].x, path[0].y, path[0].z);
  24823. vectlg = path[j].subtract(path[0]).length();
  24824. dist = vectlg + uTotalDistance[p];
  24825. us[p].push(dist);
  24826. uTotalDistance[p] = dist;
  24827. }
  24828. lg[p] = l + closePathCorr;
  24829. idx[p] = idc;
  24830. idc += (l + closePathCorr);
  24831. }
  24832. // vertical distances (v)
  24833. var path1;
  24834. var path2;
  24835. var vertex1;
  24836. var vertex2;
  24837. for (i = 0; i < minlg + closePathCorr; i++) {
  24838. vTotalDistance[i] = 0;
  24839. vs[i] = [0];
  24840. for (p = 0; p < pathArray.length - 1; p++) {
  24841. path1 = pathArray[p];
  24842. path2 = pathArray[p + 1];
  24843. if (i === minlg) {
  24844. vertex1 = path1[0];
  24845. vertex2 = path2[0];
  24846. }
  24847. else {
  24848. vertex1 = path1[i];
  24849. vertex2 = path2[i];
  24850. }
  24851. vectlg = vertex2.subtract(vertex1).length();
  24852. dist = vectlg + vTotalDistance[i];
  24853. vs[i].push(dist);
  24854. vTotalDistance[i] = dist;
  24855. }
  24856. if (closeArray) {
  24857. path1 = pathArray[p];
  24858. path2 = pathArray[0];
  24859. if (i === minlg) {
  24860. vertex2 = path2[0];
  24861. }
  24862. vectlg = vertex2.subtract(vertex1).length();
  24863. dist = vectlg + vTotalDistance[i];
  24864. vTotalDistance[i] = dist;
  24865. }
  24866. }
  24867. // uvs
  24868. var u;
  24869. var v;
  24870. for (p = 0; p < pathArray.length; p++) {
  24871. for (i = 0; i < minlg + closePathCorr; i++) {
  24872. u = us[p][i] / uTotalDistance[p];
  24873. v = vs[i][p] / vTotalDistance[i];
  24874. uvs.push(u, v);
  24875. }
  24876. }
  24877. // indices
  24878. p = 0; // path index
  24879. var pi = 0; // positions array index
  24880. var l1 = lg[p] - 1; // path1 length
  24881. var l2 = lg[p + 1] - 1; // path2 length
  24882. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24883. var shft = idx[1] - idx[0]; // shift
  24884. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24885. while (pi <= min && p < path1nb) {
  24886. // 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
  24887. indices.push(pi, pi + shft, pi + 1);
  24888. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24889. pi += 1;
  24890. if (pi === min) {
  24891. p++;
  24892. if (p === lg.length - 1) {
  24893. shft = idx[0] - idx[p];
  24894. l1 = lg[p] - 1;
  24895. l2 = lg[0] - 1;
  24896. }
  24897. else {
  24898. shft = idx[p + 1] - idx[p];
  24899. l1 = lg[p] - 1;
  24900. l2 = lg[p + 1] - 1;
  24901. }
  24902. pi = idx[p];
  24903. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24904. }
  24905. }
  24906. // normals
  24907. VertexData.ComputeNormals(positions, indices, normals);
  24908. if (closePath) {
  24909. var indexFirst = 0;
  24910. var indexLast = 0;
  24911. for (p = 0; p < pathArray.length; p++) {
  24912. indexFirst = idx[p] * 3;
  24913. if (p + 1 < pathArray.length) {
  24914. indexLast = (idx[p + 1] - 1) * 3;
  24915. }
  24916. else {
  24917. indexLast = normals.length - 3;
  24918. }
  24919. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24920. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24921. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24922. normals[indexLast] = normals[indexFirst];
  24923. normals[indexLast + 1] = normals[indexFirst + 1];
  24924. normals[indexLast + 2] = normals[indexFirst + 2];
  24925. }
  24926. }
  24927. // sides
  24928. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24929. // Result
  24930. var vertexData = new VertexData();
  24931. vertexData.indices = indices;
  24932. vertexData.positions = positions;
  24933. vertexData.normals = normals;
  24934. vertexData.uvs = uvs;
  24935. if (closePath) {
  24936. vertexData._idx = idx;
  24937. }
  24938. return vertexData;
  24939. };
  24940. VertexData.CreateBox = function (options) {
  24941. var normalsSource = [
  24942. new BABYLON.Vector3(0, 0, 1),
  24943. new BABYLON.Vector3(0, 0, -1),
  24944. new BABYLON.Vector3(1, 0, 0),
  24945. new BABYLON.Vector3(-1, 0, 0),
  24946. new BABYLON.Vector3(0, 1, 0),
  24947. new BABYLON.Vector3(0, -1, 0)
  24948. ];
  24949. var indices = [];
  24950. var positions = [];
  24951. var normals = [];
  24952. var uvs = [];
  24953. var width = options.width || options.size || 1;
  24954. var height = options.height || options.size || 1;
  24955. var depth = options.depth || options.size || 1;
  24956. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24957. var faceUV = options.faceUV || new Array(6);
  24958. var faceColors = options.faceColors;
  24959. var colors = [];
  24960. // default face colors and UV if undefined
  24961. for (var f = 0; f < 6; f++) {
  24962. if (faceUV[f] === undefined) {
  24963. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24964. }
  24965. if (faceColors && faceColors[f] === undefined) {
  24966. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24967. }
  24968. }
  24969. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24970. // Create each face in turn.
  24971. for (var index = 0; index < normalsSource.length; index++) {
  24972. var normal = normalsSource[index];
  24973. // Get two vectors perpendicular to the face normal and to each other.
  24974. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24975. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24976. // Six indices (two triangles) per face.
  24977. var verticesLength = positions.length / 3;
  24978. indices.push(verticesLength);
  24979. indices.push(verticesLength + 1);
  24980. indices.push(verticesLength + 2);
  24981. indices.push(verticesLength);
  24982. indices.push(verticesLength + 2);
  24983. indices.push(verticesLength + 3);
  24984. // Four vertices per face.
  24985. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24986. positions.push(vertex.x, vertex.y, vertex.z);
  24987. normals.push(normal.x, normal.y, normal.z);
  24988. uvs.push(faceUV[index].z, faceUV[index].w);
  24989. if (faceColors) {
  24990. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24991. }
  24992. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24993. positions.push(vertex.x, vertex.y, vertex.z);
  24994. normals.push(normal.x, normal.y, normal.z);
  24995. uvs.push(faceUV[index].x, faceUV[index].w);
  24996. if (faceColors) {
  24997. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24998. }
  24999. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25000. positions.push(vertex.x, vertex.y, vertex.z);
  25001. normals.push(normal.x, normal.y, normal.z);
  25002. uvs.push(faceUV[index].x, faceUV[index].y);
  25003. if (faceColors) {
  25004. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25005. }
  25006. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25007. positions.push(vertex.x, vertex.y, vertex.z);
  25008. normals.push(normal.x, normal.y, normal.z);
  25009. uvs.push(faceUV[index].z, faceUV[index].y);
  25010. if (faceColors) {
  25011. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25012. }
  25013. }
  25014. // sides
  25015. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25016. // Result
  25017. var vertexData = new VertexData();
  25018. vertexData.indices = indices;
  25019. vertexData.positions = positions;
  25020. vertexData.normals = normals;
  25021. vertexData.uvs = uvs;
  25022. if (faceColors) {
  25023. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25024. vertexData.colors = totalColors;
  25025. }
  25026. return vertexData;
  25027. };
  25028. VertexData.CreateSphere = function (options) {
  25029. var segments = options.segments || 32;
  25030. var diameterX = options.diameterX || options.diameter || 1;
  25031. var diameterY = options.diameterY || options.diameter || 1;
  25032. var diameterZ = options.diameterZ || options.diameter || 1;
  25033. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25034. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25035. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25036. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25037. var totalZRotationSteps = 2 + segments;
  25038. var totalYRotationSteps = 2 * totalZRotationSteps;
  25039. var indices = [];
  25040. var positions = [];
  25041. var normals = [];
  25042. var uvs = [];
  25043. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25044. var normalizedZ = zRotationStep / totalZRotationSteps;
  25045. var angleZ = normalizedZ * Math.PI * slice;
  25046. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25047. var normalizedY = yRotationStep / totalYRotationSteps;
  25048. var angleY = normalizedY * Math.PI * 2 * arc;
  25049. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25050. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25051. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25052. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25053. var vertex = complete.multiply(radius);
  25054. var normal = complete.divide(radius).normalize();
  25055. positions.push(vertex.x, vertex.y, vertex.z);
  25056. normals.push(normal.x, normal.y, normal.z);
  25057. uvs.push(normalizedY, normalizedZ);
  25058. }
  25059. if (zRotationStep > 0) {
  25060. var verticesCount = positions.length / 3;
  25061. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25062. indices.push((firstIndex));
  25063. indices.push((firstIndex + 1));
  25064. indices.push(firstIndex + totalYRotationSteps + 1);
  25065. indices.push((firstIndex + totalYRotationSteps + 1));
  25066. indices.push((firstIndex + 1));
  25067. indices.push((firstIndex + totalYRotationSteps + 2));
  25068. }
  25069. }
  25070. }
  25071. // Sides
  25072. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25073. // Result
  25074. var vertexData = new VertexData();
  25075. vertexData.indices = indices;
  25076. vertexData.positions = positions;
  25077. vertexData.normals = normals;
  25078. vertexData.uvs = uvs;
  25079. return vertexData;
  25080. };
  25081. // Cylinder and cone
  25082. VertexData.CreateCylinder = function (options) {
  25083. var height = options.height || 2;
  25084. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25085. var diameterBottom = options.diameterBottom || options.diameter || 1;
  25086. var tessellation = options.tessellation || 24;
  25087. var subdivisions = options.subdivisions || 1;
  25088. var hasRings = options.hasRings;
  25089. var enclose = options.enclose;
  25090. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25091. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25092. var faceUV = options.faceUV || new Array(3);
  25093. var faceColors = options.faceColors;
  25094. // default face colors and UV if undefined
  25095. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25096. var ringNb = (hasRings) ? subdivisions : 1;
  25097. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25098. var f;
  25099. for (f = 0; f < surfaceNb; f++) {
  25100. if (faceColors && faceColors[f] === undefined) {
  25101. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25102. }
  25103. }
  25104. for (f = 0; f < surfaceNb; f++) {
  25105. if (faceUV && faceUV[f] === undefined) {
  25106. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25107. }
  25108. }
  25109. var indices = [];
  25110. var positions = [];
  25111. var normals = [];
  25112. var uvs = [];
  25113. var colors = [];
  25114. var angle_step = Math.PI * 2 * arc / tessellation;
  25115. var angle;
  25116. var h;
  25117. var radius;
  25118. var tan = (diameterBottom - diameterTop) / 2 / height;
  25119. var ringVertex = BABYLON.Vector3.Zero();
  25120. var ringNormal = BABYLON.Vector3.Zero();
  25121. var ringFirstVertex = BABYLON.Vector3.Zero();
  25122. var ringFirstNormal = BABYLON.Vector3.Zero();
  25123. var quadNormal = BABYLON.Vector3.Zero();
  25124. var Y = BABYLON.Axis.Y;
  25125. // positions, normals, uvs
  25126. var i;
  25127. var j;
  25128. var r;
  25129. var ringIdx = 1;
  25130. var s = 1; // surface index
  25131. var cs = 0;
  25132. var v = 0;
  25133. for (i = 0; i <= subdivisions; i++) {
  25134. h = i / subdivisions;
  25135. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25136. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25137. for (r = 0; r < ringIdx; r++) {
  25138. if (hasRings) {
  25139. s += r;
  25140. }
  25141. if (enclose) {
  25142. s += 2 * r;
  25143. }
  25144. for (j = 0; j <= tessellation; j++) {
  25145. angle = j * angle_step;
  25146. // position
  25147. ringVertex.x = Math.cos(-angle) * radius;
  25148. ringVertex.y = -height / 2 + h * height;
  25149. ringVertex.z = Math.sin(-angle) * radius;
  25150. // normal
  25151. if (diameterTop === 0 && i === subdivisions) {
  25152. // if no top cap, reuse former normals
  25153. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25154. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25155. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25156. }
  25157. else {
  25158. ringNormal.x = ringVertex.x;
  25159. ringNormal.z = ringVertex.z;
  25160. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25161. ringNormal.normalize();
  25162. }
  25163. // keep first ring vertex values for enclose
  25164. if (j === 0) {
  25165. ringFirstVertex.copyFrom(ringVertex);
  25166. ringFirstNormal.copyFrom(ringNormal);
  25167. }
  25168. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25169. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25170. if (hasRings) {
  25171. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25172. }
  25173. else {
  25174. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25175. }
  25176. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25177. if (faceColors) {
  25178. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25179. }
  25180. }
  25181. // if enclose, add four vertices and their dedicated normals
  25182. if (arc !== 1 && enclose) {
  25183. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25184. positions.push(0, ringVertex.y, 0);
  25185. positions.push(0, ringVertex.y, 0);
  25186. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25187. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25188. quadNormal.normalize();
  25189. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25190. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25191. quadNormal.normalize();
  25192. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25193. if (hasRings) {
  25194. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25195. }
  25196. else {
  25197. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25198. }
  25199. uvs.push(faceUV[s + 1].x, v);
  25200. uvs.push(faceUV[s + 1].z, v);
  25201. if (hasRings) {
  25202. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25203. }
  25204. else {
  25205. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25206. }
  25207. uvs.push(faceUV[s + 2].x, v);
  25208. uvs.push(faceUV[s + 2].z, v);
  25209. if (faceColors) {
  25210. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25211. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25212. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25213. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25214. }
  25215. }
  25216. if (cs !== s) {
  25217. cs = s;
  25218. }
  25219. }
  25220. }
  25221. // indices
  25222. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25223. var s;
  25224. i = 0;
  25225. for (s = 0; s < subdivisions; s++) {
  25226. for (j = 0; j < tessellation; j++) {
  25227. var i0 = i * (e + 1) + j;
  25228. var i1 = (i + 1) * (e + 1) + j;
  25229. var i2 = i * (e + 1) + (j + 1);
  25230. var i3 = (i + 1) * (e + 1) + (j + 1);
  25231. indices.push(i0, i1, i2);
  25232. indices.push(i3, i2, i1);
  25233. }
  25234. if (arc !== 1 && enclose) {
  25235. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25236. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25237. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25238. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25239. }
  25240. i = (hasRings) ? (i + 2) : (i + 1);
  25241. }
  25242. // Caps
  25243. var createCylinderCap = function (isTop) {
  25244. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25245. if (radius === 0) {
  25246. return;
  25247. }
  25248. // Cap positions, normals & uvs
  25249. var angle;
  25250. var circleVector;
  25251. var i;
  25252. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25253. var c;
  25254. if (faceColors) {
  25255. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25256. }
  25257. // cap center
  25258. var vbase = positions.length / 3;
  25259. var offset = isTop ? height / 2 : -height / 2;
  25260. var center = new BABYLON.Vector3(0, offset, 0);
  25261. positions.push(center.x, center.y, center.z);
  25262. normals.push(0, isTop ? 1 : -1, 0);
  25263. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25264. if (faceColors) {
  25265. colors.push(c.r, c.g, c.b, c.a);
  25266. }
  25267. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25268. for (i = 0; i <= tessellation; i++) {
  25269. angle = Math.PI * 2 * i * arc / tessellation;
  25270. var cos = Math.cos(-angle);
  25271. var sin = Math.sin(-angle);
  25272. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25273. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25274. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25275. normals.push(0, isTop ? 1 : -1, 0);
  25276. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25277. if (faceColors) {
  25278. colors.push(c.r, c.g, c.b, c.a);
  25279. }
  25280. }
  25281. // Cap indices
  25282. for (i = 0; i < tessellation; i++) {
  25283. if (!isTop) {
  25284. indices.push(vbase);
  25285. indices.push(vbase + (i + 1));
  25286. indices.push(vbase + (i + 2));
  25287. }
  25288. else {
  25289. indices.push(vbase);
  25290. indices.push(vbase + (i + 2));
  25291. indices.push(vbase + (i + 1));
  25292. }
  25293. }
  25294. };
  25295. // add caps to geometry
  25296. createCylinderCap(false);
  25297. createCylinderCap(true);
  25298. // Sides
  25299. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25300. var vertexData = new VertexData();
  25301. vertexData.indices = indices;
  25302. vertexData.positions = positions;
  25303. vertexData.normals = normals;
  25304. vertexData.uvs = uvs;
  25305. if (faceColors) {
  25306. vertexData.colors = colors;
  25307. }
  25308. return vertexData;
  25309. };
  25310. VertexData.CreateTorus = function (options) {
  25311. var indices = [];
  25312. var positions = [];
  25313. var normals = [];
  25314. var uvs = [];
  25315. var diameter = options.diameter || 1;
  25316. var thickness = options.thickness || 0.5;
  25317. var tessellation = options.tessellation || 16;
  25318. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25319. var stride = tessellation + 1;
  25320. for (var i = 0; i <= tessellation; i++) {
  25321. var u = i / tessellation;
  25322. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25323. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25324. for (var j = 0; j <= tessellation; j++) {
  25325. var v = 1 - j / tessellation;
  25326. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25327. var dx = Math.cos(innerAngle);
  25328. var dy = Math.sin(innerAngle);
  25329. // Create a vertex.
  25330. var normal = new BABYLON.Vector3(dx, dy, 0);
  25331. var position = normal.scale(thickness / 2);
  25332. var textureCoordinate = new BABYLON.Vector2(u, v);
  25333. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25334. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25335. positions.push(position.x, position.y, position.z);
  25336. normals.push(normal.x, normal.y, normal.z);
  25337. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25338. // And create indices for two triangles.
  25339. var nextI = (i + 1) % stride;
  25340. var nextJ = (j + 1) % stride;
  25341. indices.push(i * stride + j);
  25342. indices.push(i * stride + nextJ);
  25343. indices.push(nextI * stride + j);
  25344. indices.push(i * stride + nextJ);
  25345. indices.push(nextI * stride + nextJ);
  25346. indices.push(nextI * stride + j);
  25347. }
  25348. }
  25349. // Sides
  25350. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25351. // Result
  25352. var vertexData = new VertexData();
  25353. vertexData.indices = indices;
  25354. vertexData.positions = positions;
  25355. vertexData.normals = normals;
  25356. vertexData.uvs = uvs;
  25357. return vertexData;
  25358. };
  25359. VertexData.CreateLineSystem = function (options) {
  25360. var indices = [];
  25361. var positions = [];
  25362. var lines = options.lines;
  25363. var idx = 0;
  25364. for (var l = 0; l < lines.length; l++) {
  25365. var points = lines[l];
  25366. for (var index = 0; index < points.length; index++) {
  25367. positions.push(points[index].x, points[index].y, points[index].z);
  25368. if (index > 0) {
  25369. indices.push(idx - 1);
  25370. indices.push(idx);
  25371. }
  25372. idx++;
  25373. }
  25374. }
  25375. var vertexData = new VertexData();
  25376. vertexData.indices = indices;
  25377. vertexData.positions = positions;
  25378. return vertexData;
  25379. };
  25380. VertexData.CreateDashedLines = function (options) {
  25381. var dashSize = options.dashSize || 3;
  25382. var gapSize = options.gapSize || 1;
  25383. var dashNb = options.dashNb || 200;
  25384. var points = options.points;
  25385. var positions = new Array();
  25386. var indices = new Array();
  25387. var curvect = BABYLON.Vector3.Zero();
  25388. var lg = 0;
  25389. var nb = 0;
  25390. var shft = 0;
  25391. var dashshft = 0;
  25392. var curshft = 0;
  25393. var idx = 0;
  25394. var i = 0;
  25395. for (i = 0; i < points.length - 1; i++) {
  25396. points[i + 1].subtractToRef(points[i], curvect);
  25397. lg += curvect.length();
  25398. }
  25399. shft = lg / dashNb;
  25400. dashshft = dashSize * shft / (dashSize + gapSize);
  25401. for (i = 0; i < points.length - 1; i++) {
  25402. points[i + 1].subtractToRef(points[i], curvect);
  25403. nb = Math.floor(curvect.length() / shft);
  25404. curvect.normalize();
  25405. for (var j = 0; j < nb; j++) {
  25406. curshft = shft * j;
  25407. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25408. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25409. indices.push(idx, idx + 1);
  25410. idx += 2;
  25411. }
  25412. }
  25413. // Result
  25414. var vertexData = new VertexData();
  25415. vertexData.positions = positions;
  25416. vertexData.indices = indices;
  25417. return vertexData;
  25418. };
  25419. VertexData.CreateGround = function (options) {
  25420. var indices = [];
  25421. var positions = [];
  25422. var normals = [];
  25423. var uvs = [];
  25424. var row, col;
  25425. var width = options.width || 1;
  25426. var height = options.height || 1;
  25427. var subdivisions = options.subdivisions || 1;
  25428. for (row = 0; row <= subdivisions; row++) {
  25429. for (col = 0; col <= subdivisions; col++) {
  25430. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25431. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25432. positions.push(position.x, position.y, position.z);
  25433. normals.push(normal.x, normal.y, normal.z);
  25434. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25435. }
  25436. }
  25437. for (row = 0; row < subdivisions; row++) {
  25438. for (col = 0; col < subdivisions; col++) {
  25439. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25440. indices.push(col + 1 + row * (subdivisions + 1));
  25441. indices.push(col + row * (subdivisions + 1));
  25442. indices.push(col + (row + 1) * (subdivisions + 1));
  25443. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25444. indices.push(col + row * (subdivisions + 1));
  25445. }
  25446. }
  25447. // Result
  25448. var vertexData = new VertexData();
  25449. vertexData.indices = indices;
  25450. vertexData.positions = positions;
  25451. vertexData.normals = normals;
  25452. vertexData.uvs = uvs;
  25453. return vertexData;
  25454. };
  25455. VertexData.CreateTiledGround = function (options) {
  25456. var xmin = options.xmin;
  25457. var zmin = options.zmin;
  25458. var xmax = options.xmax;
  25459. var zmax = options.zmax;
  25460. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25461. var precision = options.precision || { w: 1, h: 1 };
  25462. var indices = [];
  25463. var positions = [];
  25464. var normals = [];
  25465. var uvs = [];
  25466. var row, col, tileRow, tileCol;
  25467. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25468. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25469. precision.w = (precision.w < 1) ? 1 : precision.w;
  25470. precision.h = (precision.h < 1) ? 1 : precision.h;
  25471. var tileSize = {
  25472. 'w': (xmax - xmin) / subdivisions.w,
  25473. 'h': (zmax - zmin) / subdivisions.h
  25474. };
  25475. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25476. // Indices
  25477. var base = positions.length / 3;
  25478. var rowLength = precision.w + 1;
  25479. for (row = 0; row < precision.h; row++) {
  25480. for (col = 0; col < precision.w; col++) {
  25481. var square = [
  25482. base + col + row * rowLength,
  25483. base + (col + 1) + row * rowLength,
  25484. base + (col + 1) + (row + 1) * rowLength,
  25485. base + col + (row + 1) * rowLength
  25486. ];
  25487. indices.push(square[1]);
  25488. indices.push(square[2]);
  25489. indices.push(square[3]);
  25490. indices.push(square[0]);
  25491. indices.push(square[1]);
  25492. indices.push(square[3]);
  25493. }
  25494. }
  25495. // Position, normals and uvs
  25496. var position = BABYLON.Vector3.Zero();
  25497. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25498. for (row = 0; row <= precision.h; row++) {
  25499. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25500. for (col = 0; col <= precision.w; col++) {
  25501. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25502. position.y = 0;
  25503. positions.push(position.x, position.y, position.z);
  25504. normals.push(normal.x, normal.y, normal.z);
  25505. uvs.push(col / precision.w, row / precision.h);
  25506. }
  25507. }
  25508. }
  25509. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25510. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25511. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25512. }
  25513. }
  25514. // Result
  25515. var vertexData = new VertexData();
  25516. vertexData.indices = indices;
  25517. vertexData.positions = positions;
  25518. vertexData.normals = normals;
  25519. vertexData.uvs = uvs;
  25520. return vertexData;
  25521. };
  25522. VertexData.CreateGroundFromHeightMap = function (options) {
  25523. var indices = [];
  25524. var positions = [];
  25525. var normals = [];
  25526. var uvs = [];
  25527. var row, col;
  25528. // Vertices
  25529. for (row = 0; row <= options.subdivisions; row++) {
  25530. for (col = 0; col <= options.subdivisions; col++) {
  25531. 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));
  25532. // Compute height
  25533. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25534. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25535. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25536. var r = options.buffer[pos] / 255.0;
  25537. var g = options.buffer[pos + 1] / 255.0;
  25538. var b = options.buffer[pos + 2] / 255.0;
  25539. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25540. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25541. // Add vertex
  25542. positions.push(position.x, position.y, position.z);
  25543. normals.push(0, 0, 0);
  25544. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25545. }
  25546. }
  25547. // Indices
  25548. for (row = 0; row < options.subdivisions; row++) {
  25549. for (col = 0; col < options.subdivisions; col++) {
  25550. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25551. indices.push(col + 1 + row * (options.subdivisions + 1));
  25552. indices.push(col + row * (options.subdivisions + 1));
  25553. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25554. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25555. indices.push(col + row * (options.subdivisions + 1));
  25556. }
  25557. }
  25558. // Normals
  25559. VertexData.ComputeNormals(positions, indices, normals);
  25560. // Result
  25561. var vertexData = new VertexData();
  25562. vertexData.indices = indices;
  25563. vertexData.positions = positions;
  25564. vertexData.normals = normals;
  25565. vertexData.uvs = uvs;
  25566. return vertexData;
  25567. };
  25568. VertexData.CreatePlane = function (options) {
  25569. var indices = [];
  25570. var positions = [];
  25571. var normals = [];
  25572. var uvs = [];
  25573. var width = options.width || options.size || 1;
  25574. var height = options.height || options.size || 1;
  25575. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25576. // Vertices
  25577. var halfWidth = width / 2.0;
  25578. var halfHeight = height / 2.0;
  25579. positions.push(-halfWidth, -halfHeight, 0);
  25580. normals.push(0, 0, -1.0);
  25581. uvs.push(0.0, 0.0);
  25582. positions.push(halfWidth, -halfHeight, 0);
  25583. normals.push(0, 0, -1.0);
  25584. uvs.push(1.0, 0.0);
  25585. positions.push(halfWidth, halfHeight, 0);
  25586. normals.push(0, 0, -1.0);
  25587. uvs.push(1.0, 1.0);
  25588. positions.push(-halfWidth, halfHeight, 0);
  25589. normals.push(0, 0, -1.0);
  25590. uvs.push(0.0, 1.0);
  25591. // Indices
  25592. indices.push(0);
  25593. indices.push(1);
  25594. indices.push(2);
  25595. indices.push(0);
  25596. indices.push(2);
  25597. indices.push(3);
  25598. // Sides
  25599. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25600. // Result
  25601. var vertexData = new VertexData();
  25602. vertexData.indices = indices;
  25603. vertexData.positions = positions;
  25604. vertexData.normals = normals;
  25605. vertexData.uvs = uvs;
  25606. return vertexData;
  25607. };
  25608. VertexData.CreateDisc = function (options) {
  25609. var positions = [];
  25610. var indices = [];
  25611. var normals = [];
  25612. var uvs = [];
  25613. var radius = options.radius || 0.5;
  25614. var tessellation = options.tessellation || 64;
  25615. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25616. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25617. // positions and uvs
  25618. positions.push(0, 0, 0); // disc center first
  25619. uvs.push(0.5, 0.5);
  25620. var theta = Math.PI * 2 * arc;
  25621. var step = theta / tessellation;
  25622. for (var a = 0; a < theta; a += step) {
  25623. var x = Math.cos(a);
  25624. var y = Math.sin(a);
  25625. var u = (x + 1) / 2;
  25626. var v = (1 - y) / 2;
  25627. positions.push(radius * x, radius * y, 0);
  25628. uvs.push(u, v);
  25629. }
  25630. if (arc === 1) {
  25631. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25632. uvs.push(uvs[2], uvs[3]);
  25633. }
  25634. //indices
  25635. var vertexNb = positions.length / 3;
  25636. for (var i = 1; i < vertexNb - 1; i++) {
  25637. indices.push(i + 1, 0, i);
  25638. }
  25639. // result
  25640. VertexData.ComputeNormals(positions, indices, normals);
  25641. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25642. var vertexData = new VertexData();
  25643. vertexData.indices = indices;
  25644. vertexData.positions = positions;
  25645. vertexData.normals = normals;
  25646. vertexData.uvs = uvs;
  25647. return vertexData;
  25648. };
  25649. VertexData.CreateIcoSphere = function (options) {
  25650. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25651. var radius = options.radius || 1;
  25652. var flat = (options.flat === undefined) ? true : options.flat;
  25653. var subdivisions = options.subdivisions || 4;
  25654. var radiusX = options.radiusX || radius;
  25655. var radiusY = options.radiusY || radius;
  25656. var radiusZ = options.radiusZ || radius;
  25657. var t = (1 + Math.sqrt(5)) / 2;
  25658. // 12 vertex x,y,z
  25659. var ico_vertices = [
  25660. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25661. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25662. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25663. ];
  25664. // index of 3 vertex makes a face of icopshere
  25665. var ico_indices = [
  25666. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25667. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25668. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25669. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25670. ];
  25671. // vertex for uv have aliased position, not for UV
  25672. var vertices_unalias_id = [
  25673. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25674. // vertex alias
  25675. 0,
  25676. 2,
  25677. 3,
  25678. 3,
  25679. 3,
  25680. 4,
  25681. 7,
  25682. 8,
  25683. 9,
  25684. 9,
  25685. 10,
  25686. 11 // 23: B + 12
  25687. ];
  25688. // uv as integer step (not pixels !)
  25689. var ico_vertexuv = [
  25690. 5, 1, 3, 1, 6, 4, 0, 0,
  25691. 5, 3, 4, 2, 2, 2, 4, 0,
  25692. 2, 0, 1, 1, 6, 0, 6, 2,
  25693. // vertex alias (for same vertex on different faces)
  25694. 0, 4,
  25695. 3, 3,
  25696. 4, 4,
  25697. 3, 1,
  25698. 4, 2,
  25699. 4, 4,
  25700. 0, 2,
  25701. 1, 1,
  25702. 2, 2,
  25703. 3, 3,
  25704. 1, 3,
  25705. 2, 4 // 23: B + 12
  25706. ];
  25707. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25708. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25709. // First island of uv mapping
  25710. // v = 4h 3+ 2
  25711. // v = 3h 9+ 4
  25712. // v = 2h 9+ 5 B
  25713. // v = 1h 9 1 0
  25714. // v = 0h 3 8 7 A
  25715. // u = 0 1 2 3 4 5 6 *a
  25716. // Second island of uv mapping
  25717. // v = 4h 0+ B+ 4+
  25718. // v = 3h A+ 2+
  25719. // v = 2h 7+ 6 3+
  25720. // v = 1h 8+ 3+
  25721. // v = 0h
  25722. // u = 0 1 2 3 4 5 6 *a
  25723. // Face layout on texture UV mapping
  25724. // ============
  25725. // \ 4 /\ 16 / ======
  25726. // \ / \ / /\ 11 /
  25727. // \/ 7 \/ / \ /
  25728. // ======= / 10 \/
  25729. // /\ 17 /\ =======
  25730. // / \ / \ \ 15 /\
  25731. // / 8 \/ 12 \ \ / \
  25732. // ============ \/ 6 \
  25733. // \ 18 /\ ============
  25734. // \ / \ \ 5 /\ 0 /
  25735. // \/ 13 \ \ / \ /
  25736. // ======= \/ 1 \/
  25737. // =============
  25738. // /\ 19 /\ 2 /\
  25739. // / \ / \ / \
  25740. // / 14 \/ 9 \/ 3 \
  25741. // ===================
  25742. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25743. var ustep = 138 / 1024;
  25744. var vstep = 239 / 1024;
  25745. var uoffset = 60 / 1024;
  25746. var voffset = 26 / 1024;
  25747. // Second island should have margin, not to touch the first island
  25748. // avoid any borderline artefact in pixel rounding
  25749. var island_u_offset = -40 / 1024;
  25750. var island_v_offset = +20 / 1024;
  25751. // face is either island 0 or 1 :
  25752. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25753. var island = [
  25754. 0, 0, 0, 0, 1,
  25755. 0, 0, 1, 1, 0,
  25756. 0, 0, 1, 1, 0,
  25757. 0, 1, 1, 1, 0 // 15 - 19
  25758. ];
  25759. var indices = [];
  25760. var positions = [];
  25761. var normals = [];
  25762. var uvs = [];
  25763. var current_indice = 0;
  25764. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25765. var face_vertex_pos = new Array(3);
  25766. var face_vertex_uv = new Array(3);
  25767. var v012;
  25768. for (v012 = 0; v012 < 3; v012++) {
  25769. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25770. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25771. }
  25772. // create all with normals
  25773. for (var face = 0; face < 20; face++) {
  25774. // 3 vertex per face
  25775. for (v012 = 0; v012 < 3; v012++) {
  25776. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25777. var v_id = ico_indices[3 * face + v012];
  25778. // vertex have 3D position (x,y,z)
  25779. 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]);
  25780. // Normalize to get normal, then scale to radius
  25781. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25782. // uv Coordinates from vertex ID
  25783. 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);
  25784. }
  25785. // Subdivide the face (interpolate pos, norm, uv)
  25786. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25787. // - norm is linear interpolation of vertex corner normal
  25788. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25789. // - uv is linear interpolation
  25790. //
  25791. // Topology is as below for sub-divide by 2
  25792. // vertex shown as v0,v1,v2
  25793. // interp index is i1 to progress in range [v0,v1[
  25794. // interp index is i2 to progress in range [v0,v2[
  25795. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25796. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25797. //
  25798. //
  25799. // i2 v2
  25800. // ^ ^
  25801. // / / \
  25802. // / / \
  25803. // / / \
  25804. // / / (0,1) \
  25805. // / #---------\
  25806. // / / \ (0,0)'/ \
  25807. // / / \ / \
  25808. // / / \ / \
  25809. // / / (0,0) \ / (1,0) \
  25810. // / #---------#---------\
  25811. // v0 v1
  25812. //
  25813. // --------------------> i1
  25814. //
  25815. // interp of (i1,i2):
  25816. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25817. // along i1 : lerp(x0,x1, i1/(S-i2))
  25818. //
  25819. // centroid of triangle is needed to get help normal computation
  25820. // (c1,c2) are used for centroid location
  25821. var interp_vertex = function (i1, i2, c1, c2) {
  25822. // vertex is interpolated from
  25823. // - face_vertex_pos[0..2]
  25824. // - face_vertex_uv[0..2]
  25825. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25826. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25827. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25828. pos_interp.normalize();
  25829. var vertex_normal;
  25830. if (flat) {
  25831. // in flat mode, recalculate normal as face centroid normal
  25832. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25833. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25834. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25835. }
  25836. else {
  25837. // in smooth mode, recalculate normal from each single vertex position
  25838. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25839. }
  25840. // Vertex normal need correction due to X,Y,Z radius scaling
  25841. vertex_normal.x /= radiusX;
  25842. vertex_normal.y /= radiusY;
  25843. vertex_normal.z /= radiusZ;
  25844. vertex_normal.normalize();
  25845. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25846. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25847. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25848. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25849. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25850. uvs.push(uv_interp.x, uv_interp.y);
  25851. // push each vertex has member of a face
  25852. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25853. indices.push(current_indice);
  25854. current_indice++;
  25855. };
  25856. for (var i2 = 0; i2 < subdivisions; i2++) {
  25857. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25858. // face : (i1,i2) for /\ :
  25859. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25860. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25861. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25862. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25863. if (i1 + i2 + 1 < subdivisions) {
  25864. // face : (i1,i2)' for \/ :
  25865. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25866. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25867. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25868. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25869. }
  25870. }
  25871. }
  25872. }
  25873. // Sides
  25874. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25875. // Result
  25876. var vertexData = new VertexData();
  25877. vertexData.indices = indices;
  25878. vertexData.positions = positions;
  25879. vertexData.normals = normals;
  25880. vertexData.uvs = uvs;
  25881. return vertexData;
  25882. };
  25883. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25884. VertexData.CreatePolyhedron = function (options) {
  25885. // provided polyhedron types :
  25886. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25887. // 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)
  25888. var polyhedra = [];
  25889. 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]] };
  25890. 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]] };
  25891. polyhedra[2] = {
  25892. 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]],
  25893. 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]]
  25894. };
  25895. polyhedra[3] = {
  25896. 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]],
  25897. 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]]
  25898. };
  25899. polyhedra[4] = {
  25900. 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]],
  25901. 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]]
  25902. };
  25903. 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]] };
  25904. 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]] };
  25905. 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]] };
  25906. 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]] };
  25907. 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]] };
  25908. 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]] };
  25909. 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]] };
  25910. 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]] };
  25911. 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]] };
  25912. polyhedra[14] = {
  25913. 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]],
  25914. 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]]
  25915. };
  25916. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25917. var size = options.size;
  25918. var sizeX = options.sizeX || size || 1;
  25919. var sizeY = options.sizeY || size || 1;
  25920. var sizeZ = options.sizeZ || size || 1;
  25921. var data = options.custom || polyhedra[type];
  25922. var nbfaces = data.face.length;
  25923. var faceUV = options.faceUV || new Array(nbfaces);
  25924. var faceColors = options.faceColors;
  25925. var flat = (options.flat === undefined) ? true : options.flat;
  25926. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25927. var positions = [];
  25928. var indices = [];
  25929. var normals = [];
  25930. var uvs = [];
  25931. var colors = [];
  25932. var index = 0;
  25933. var faceIdx = 0; // face cursor in the array "indexes"
  25934. var indexes = [];
  25935. var i = 0;
  25936. var f = 0;
  25937. var u, v, ang, x, y, tmp;
  25938. // default face colors and UV if undefined
  25939. if (flat) {
  25940. for (f = 0; f < nbfaces; f++) {
  25941. if (faceColors && faceColors[f] === undefined) {
  25942. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25943. }
  25944. if (faceUV && faceUV[f] === undefined) {
  25945. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25946. }
  25947. }
  25948. }
  25949. if (!flat) {
  25950. for (i = 0; i < data.vertex.length; i++) {
  25951. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25952. uvs.push(0, 0);
  25953. }
  25954. for (f = 0; f < nbfaces; f++) {
  25955. for (i = 0; i < data.face[f].length - 2; i++) {
  25956. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25957. }
  25958. }
  25959. }
  25960. else {
  25961. for (f = 0; f < nbfaces; f++) {
  25962. var fl = data.face[f].length; // number of vertices of the current face
  25963. ang = 2 * Math.PI / fl;
  25964. x = 0.5 * Math.tan(ang / 2);
  25965. y = 0.5;
  25966. // positions, uvs, colors
  25967. for (i = 0; i < fl; i++) {
  25968. // positions
  25969. 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);
  25970. indexes.push(index);
  25971. index++;
  25972. // uvs
  25973. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25974. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25975. uvs.push(u, v);
  25976. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25977. y = x * Math.sin(ang) + y * Math.cos(ang);
  25978. x = tmp;
  25979. // colors
  25980. if (faceColors) {
  25981. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25982. }
  25983. }
  25984. // indices from indexes
  25985. for (i = 0; i < fl - 2; i++) {
  25986. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25987. }
  25988. faceIdx += fl;
  25989. }
  25990. }
  25991. VertexData.ComputeNormals(positions, indices, normals);
  25992. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25993. var vertexData = new VertexData();
  25994. vertexData.positions = positions;
  25995. vertexData.indices = indices;
  25996. vertexData.normals = normals;
  25997. vertexData.uvs = uvs;
  25998. if (faceColors && flat) {
  25999. vertexData.colors = colors;
  26000. }
  26001. return vertexData;
  26002. };
  26003. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26004. VertexData.CreateTorusKnot = function (options) {
  26005. var indices = [];
  26006. var positions = [];
  26007. var normals = [];
  26008. var uvs = [];
  26009. var radius = options.radius || 2;
  26010. var tube = options.tube || 0.5;
  26011. var radialSegments = options.radialSegments || 32;
  26012. var tubularSegments = options.tubularSegments || 32;
  26013. var p = options.p || 2;
  26014. var q = options.q || 3;
  26015. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26016. // Helper
  26017. var getPos = function (angle) {
  26018. var cu = Math.cos(angle);
  26019. var su = Math.sin(angle);
  26020. var quOverP = q / p * angle;
  26021. var cs = Math.cos(quOverP);
  26022. var tx = radius * (2 + cs) * 0.5 * cu;
  26023. var ty = radius * (2 + cs) * su * 0.5;
  26024. var tz = radius * Math.sin(quOverP) * 0.5;
  26025. return new BABYLON.Vector3(tx, ty, tz);
  26026. };
  26027. // Vertices
  26028. var i;
  26029. var j;
  26030. for (i = 0; i <= radialSegments; i++) {
  26031. var modI = i % radialSegments;
  26032. var u = modI / radialSegments * 2 * p * Math.PI;
  26033. var p1 = getPos(u);
  26034. var p2 = getPos(u + 0.01);
  26035. var tang = p2.subtract(p1);
  26036. var n = p2.add(p1);
  26037. var bitan = BABYLON.Vector3.Cross(tang, n);
  26038. n = BABYLON.Vector3.Cross(bitan, tang);
  26039. bitan.normalize();
  26040. n.normalize();
  26041. for (j = 0; j < tubularSegments; j++) {
  26042. var modJ = j % tubularSegments;
  26043. var v = modJ / tubularSegments * 2 * Math.PI;
  26044. var cx = -tube * Math.cos(v);
  26045. var cy = tube * Math.sin(v);
  26046. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26047. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26048. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26049. uvs.push(i / radialSegments);
  26050. uvs.push(j / tubularSegments);
  26051. }
  26052. }
  26053. for (i = 0; i < radialSegments; i++) {
  26054. for (j = 0; j < tubularSegments; j++) {
  26055. var jNext = (j + 1) % tubularSegments;
  26056. var a = i * tubularSegments + j;
  26057. var b = (i + 1) * tubularSegments + j;
  26058. var c = (i + 1) * tubularSegments + jNext;
  26059. var d = i * tubularSegments + jNext;
  26060. indices.push(d);
  26061. indices.push(b);
  26062. indices.push(a);
  26063. indices.push(d);
  26064. indices.push(c);
  26065. indices.push(b);
  26066. }
  26067. }
  26068. // Normals
  26069. VertexData.ComputeNormals(positions, indices, normals);
  26070. // Sides
  26071. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26072. // Result
  26073. var vertexData = new VertexData();
  26074. vertexData.indices = indices;
  26075. vertexData.positions = positions;
  26076. vertexData.normals = normals;
  26077. vertexData.uvs = uvs;
  26078. return vertexData;
  26079. };
  26080. // Tools
  26081. /**
  26082. * @param {any} - positions (number[] or Float32Array)
  26083. * @param {any} - indices (number[] or Uint16Array)
  26084. * @param {any} - normals (number[] or Float32Array)
  26085. */
  26086. VertexData.ComputeNormals = function (positions, indices, normals) {
  26087. var index = 0;
  26088. var p1p2x = 0.0;
  26089. var p1p2y = 0.0;
  26090. var p1p2z = 0.0;
  26091. var p3p2x = 0.0;
  26092. var p3p2y = 0.0;
  26093. var p3p2z = 0.0;
  26094. var faceNormalx = 0.0;
  26095. var faceNormaly = 0.0;
  26096. var faceNormalz = 0.0;
  26097. var length = 0.0;
  26098. var i1 = 0;
  26099. var i2 = 0;
  26100. var i3 = 0;
  26101. for (index = 0; index < positions.length; index++) {
  26102. normals[index] = 0.0;
  26103. }
  26104. // indice triplet = 1 face
  26105. var nbFaces = indices.length / 3;
  26106. for (index = 0; index < nbFaces; index++) {
  26107. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  26108. i2 = indices[index * 3 + 1];
  26109. i3 = indices[index * 3 + 2];
  26110. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  26111. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  26112. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  26113. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  26114. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  26115. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  26116. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  26117. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  26118. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  26119. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26120. length = (length === 0) ? 1.0 : length;
  26121. faceNormalx /= length; // normalize this normal
  26122. faceNormaly /= length;
  26123. faceNormalz /= length;
  26124. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  26125. normals[i1 * 3 + 1] += faceNormaly;
  26126. normals[i1 * 3 + 2] += faceNormalz;
  26127. normals[i2 * 3] += faceNormalx;
  26128. normals[i2 * 3 + 1] += faceNormaly;
  26129. normals[i2 * 3 + 2] += faceNormalz;
  26130. normals[i3 * 3] += faceNormalx;
  26131. normals[i3 * 3 + 1] += faceNormaly;
  26132. normals[i3 * 3 + 2] += faceNormalz;
  26133. }
  26134. // last normalization of each normal
  26135. for (index = 0; index < normals.length / 3; index++) {
  26136. faceNormalx = normals[index * 3];
  26137. faceNormaly = normals[index * 3 + 1];
  26138. faceNormalz = normals[index * 3 + 2];
  26139. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26140. length = (length === 0) ? 1.0 : length;
  26141. faceNormalx /= length;
  26142. faceNormaly /= length;
  26143. faceNormalz /= length;
  26144. normals[index * 3] = faceNormalx;
  26145. normals[index * 3 + 1] = faceNormaly;
  26146. normals[index * 3 + 2] = faceNormalz;
  26147. }
  26148. };
  26149. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26150. var li = indices.length;
  26151. var ln = normals.length;
  26152. var i;
  26153. var n;
  26154. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26155. switch (sideOrientation) {
  26156. case BABYLON.Mesh.FRONTSIDE:
  26157. // nothing changed
  26158. break;
  26159. case BABYLON.Mesh.BACKSIDE:
  26160. var tmp;
  26161. // indices
  26162. for (i = 0; i < li; i += 3) {
  26163. tmp = indices[i];
  26164. indices[i] = indices[i + 2];
  26165. indices[i + 2] = tmp;
  26166. }
  26167. // normals
  26168. for (n = 0; n < ln; n++) {
  26169. normals[n] = -normals[n];
  26170. }
  26171. break;
  26172. case BABYLON.Mesh.DOUBLESIDE:
  26173. // positions
  26174. var lp = positions.length;
  26175. var l = lp / 3;
  26176. for (var p = 0; p < lp; p++) {
  26177. positions[lp + p] = positions[p];
  26178. }
  26179. // indices
  26180. for (i = 0; i < li; i += 3) {
  26181. indices[i + li] = indices[i + 2] + l;
  26182. indices[i + 1 + li] = indices[i + 1] + l;
  26183. indices[i + 2 + li] = indices[i] + l;
  26184. }
  26185. // normals
  26186. for (n = 0; n < ln; n++) {
  26187. normals[ln + n] = -normals[n];
  26188. }
  26189. // uvs
  26190. var lu = uvs.length;
  26191. for (var u = 0; u < lu; u++) {
  26192. uvs[u + lu] = uvs[u];
  26193. }
  26194. break;
  26195. }
  26196. };
  26197. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26198. var vertexData = new VertexData();
  26199. // positions
  26200. var positions = parsedVertexData.positions;
  26201. if (positions) {
  26202. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26203. }
  26204. // normals
  26205. var normals = parsedVertexData.normals;
  26206. if (normals) {
  26207. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26208. }
  26209. // uvs
  26210. var uvs = parsedVertexData.uvs;
  26211. if (uvs) {
  26212. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26213. }
  26214. // uv2s
  26215. var uv2s = parsedVertexData.uv2s;
  26216. if (uv2s) {
  26217. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26218. }
  26219. // uv3s
  26220. var uv3s = parsedVertexData.uv3s;
  26221. if (uv3s) {
  26222. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26223. }
  26224. // uv4s
  26225. var uv4s = parsedVertexData.uv4s;
  26226. if (uv4s) {
  26227. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26228. }
  26229. // uv5s
  26230. var uv5s = parsedVertexData.uv5s;
  26231. if (uv5s) {
  26232. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26233. }
  26234. // uv6s
  26235. var uv6s = parsedVertexData.uv6s;
  26236. if (uv6s) {
  26237. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26238. }
  26239. // colors
  26240. var colors = parsedVertexData.colors;
  26241. if (colors) {
  26242. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26243. }
  26244. // matricesIndices
  26245. var matricesIndices = parsedVertexData.matricesIndices;
  26246. if (matricesIndices) {
  26247. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26248. }
  26249. // matricesWeights
  26250. var matricesWeights = parsedVertexData.matricesWeights;
  26251. if (matricesWeights) {
  26252. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26253. }
  26254. // indices
  26255. var indices = parsedVertexData.indices;
  26256. if (indices) {
  26257. vertexData.indices = indices;
  26258. }
  26259. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26260. };
  26261. return VertexData;
  26262. })();
  26263. BABYLON.VertexData = VertexData;
  26264. })(BABYLON || (BABYLON = {}));
  26265. var BABYLON;
  26266. (function (BABYLON) {
  26267. var Tags = (function () {
  26268. function Tags() {
  26269. }
  26270. Tags.EnableFor = function (obj) {
  26271. obj._tags = obj._tags || {};
  26272. obj.hasTags = function () {
  26273. return Tags.HasTags(obj);
  26274. };
  26275. obj.addTags = function (tagsString) {
  26276. return Tags.AddTagsTo(obj, tagsString);
  26277. };
  26278. obj.removeTags = function (tagsString) {
  26279. return Tags.RemoveTagsFrom(obj, tagsString);
  26280. };
  26281. obj.matchesTagsQuery = function (tagsQuery) {
  26282. return Tags.MatchesQuery(obj, tagsQuery);
  26283. };
  26284. };
  26285. Tags.DisableFor = function (obj) {
  26286. delete obj._tags;
  26287. delete obj.hasTags;
  26288. delete obj.addTags;
  26289. delete obj.removeTags;
  26290. delete obj.matchesTagsQuery;
  26291. };
  26292. Tags.HasTags = function (obj) {
  26293. if (!obj._tags) {
  26294. return false;
  26295. }
  26296. return !BABYLON.Tools.IsEmpty(obj._tags);
  26297. };
  26298. Tags.GetTags = function (obj, asString) {
  26299. if (asString === void 0) { asString = true; }
  26300. if (!obj._tags) {
  26301. return null;
  26302. }
  26303. if (asString) {
  26304. var tagsArray = [];
  26305. for (var tag in obj._tags) {
  26306. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  26307. tagsArray.push(tag);
  26308. }
  26309. }
  26310. return tagsArray.join(" ");
  26311. }
  26312. else {
  26313. return obj._tags;
  26314. }
  26315. };
  26316. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26317. // a tag cannot start with '||', '&&', and '!'
  26318. // it cannot contain whitespaces
  26319. Tags.AddTagsTo = function (obj, tagsString) {
  26320. if (!tagsString) {
  26321. return;
  26322. }
  26323. if (typeof tagsString !== "string") {
  26324. return;
  26325. }
  26326. var tags = tagsString.split(" ");
  26327. for (var t in tags) {
  26328. Tags._AddTagTo(obj, tags[t]);
  26329. }
  26330. };
  26331. Tags._AddTagTo = function (obj, tag) {
  26332. tag = tag.trim();
  26333. if (tag === "" || tag === "true" || tag === "false") {
  26334. return;
  26335. }
  26336. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26337. return;
  26338. }
  26339. Tags.EnableFor(obj);
  26340. obj._tags[tag] = true;
  26341. };
  26342. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26343. if (!Tags.HasTags(obj)) {
  26344. return;
  26345. }
  26346. var tags = tagsString.split(" ");
  26347. for (var t in tags) {
  26348. Tags._RemoveTagFrom(obj, tags[t]);
  26349. }
  26350. };
  26351. Tags._RemoveTagFrom = function (obj, tag) {
  26352. delete obj._tags[tag];
  26353. };
  26354. Tags.MatchesQuery = function (obj, tagsQuery) {
  26355. if (tagsQuery === undefined) {
  26356. return true;
  26357. }
  26358. if (tagsQuery === "") {
  26359. return Tags.HasTags(obj);
  26360. }
  26361. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26362. };
  26363. return Tags;
  26364. })();
  26365. BABYLON.Tags = Tags;
  26366. })(BABYLON || (BABYLON = {}));
  26367. var BABYLON;
  26368. (function (BABYLON) {
  26369. var Internals;
  26370. (function (Internals) {
  26371. var AndOrNotEvaluator = (function () {
  26372. function AndOrNotEvaluator() {
  26373. }
  26374. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26375. if (!query.match(/\([^\(\)]*\)/g)) {
  26376. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26377. }
  26378. else {
  26379. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26380. // remove parenthesis
  26381. r = r.slice(1, r.length - 1);
  26382. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26383. });
  26384. }
  26385. if (query === "true") {
  26386. return true;
  26387. }
  26388. if (query === "false") {
  26389. return false;
  26390. }
  26391. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26392. };
  26393. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26394. evaluateCallback = evaluateCallback || (function (r) {
  26395. return r === "true" ? true : false;
  26396. });
  26397. var result;
  26398. var or = parenthesisContent.split("||");
  26399. for (var i in or) {
  26400. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26401. var and = ori.split("&&");
  26402. if (and.length > 1) {
  26403. for (var j = 0; j < and.length; ++j) {
  26404. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26405. if (andj !== "true" && andj !== "false") {
  26406. if (andj[0] === "!") {
  26407. result = !evaluateCallback(andj.substring(1));
  26408. }
  26409. else {
  26410. result = evaluateCallback(andj);
  26411. }
  26412. }
  26413. else {
  26414. result = andj === "true" ? true : false;
  26415. }
  26416. if (!result) {
  26417. ori = "false";
  26418. break;
  26419. }
  26420. }
  26421. }
  26422. if (result || ori === "true") {
  26423. result = true;
  26424. break;
  26425. }
  26426. // result equals false (or undefined)
  26427. if (ori !== "true" && ori !== "false") {
  26428. if (ori[0] === "!") {
  26429. result = !evaluateCallback(ori.substring(1));
  26430. }
  26431. else {
  26432. result = evaluateCallback(ori);
  26433. }
  26434. }
  26435. else {
  26436. result = ori === "true" ? true : false;
  26437. }
  26438. }
  26439. // the whole parenthesis scope is replaced by 'true' or 'false'
  26440. return result ? "true" : "false";
  26441. };
  26442. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26443. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26444. // remove whitespaces
  26445. r = r.replace(/[\s]/g, function () { return ""; });
  26446. return r.length % 2 ? "!" : "";
  26447. });
  26448. booleanString = booleanString.trim();
  26449. if (booleanString === "!true") {
  26450. booleanString = "false";
  26451. }
  26452. else if (booleanString === "!false") {
  26453. booleanString = "true";
  26454. }
  26455. return booleanString;
  26456. };
  26457. return AndOrNotEvaluator;
  26458. })();
  26459. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26460. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26461. })(BABYLON || (BABYLON = {}));
  26462. var BABYLON;
  26463. (function (BABYLON) {
  26464. var PostProcessRenderPass = (function () {
  26465. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26466. this._enabled = true;
  26467. this._refCount = 0;
  26468. this._name = name;
  26469. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26470. this.setRenderList(renderList);
  26471. this._renderTexture.onBeforeRender = beforeRender;
  26472. this._renderTexture.onAfterRender = afterRender;
  26473. this._scene = scene;
  26474. this._renderList = renderList;
  26475. }
  26476. // private
  26477. PostProcessRenderPass.prototype._incRefCount = function () {
  26478. if (this._refCount === 0) {
  26479. this._scene.customRenderTargets.push(this._renderTexture);
  26480. }
  26481. return ++this._refCount;
  26482. };
  26483. PostProcessRenderPass.prototype._decRefCount = function () {
  26484. this._refCount--;
  26485. if (this._refCount <= 0) {
  26486. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26487. }
  26488. return this._refCount;
  26489. };
  26490. PostProcessRenderPass.prototype._update = function () {
  26491. this.setRenderList(this._renderList);
  26492. };
  26493. // public
  26494. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26495. this._renderTexture.renderList = renderList;
  26496. };
  26497. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26498. return this._renderTexture;
  26499. };
  26500. return PostProcessRenderPass;
  26501. })();
  26502. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26503. })(BABYLON || (BABYLON = {}));
  26504. var BABYLON;
  26505. (function (BABYLON) {
  26506. var PostProcessRenderEffect = (function () {
  26507. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26508. this._engine = engine;
  26509. this._name = name;
  26510. this._singleInstance = singleInstance || true;
  26511. this._getPostProcess = getPostProcess;
  26512. this._cameras = [];
  26513. this._indicesForCamera = [];
  26514. this._postProcesses = {};
  26515. this._renderPasses = {};
  26516. this._renderEffectAsPasses = {};
  26517. }
  26518. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  26519. get: function () {
  26520. for (var index in this._postProcesses) {
  26521. if (!this._postProcesses[index].isSupported) {
  26522. return false;
  26523. }
  26524. }
  26525. return true;
  26526. },
  26527. enumerable: true,
  26528. configurable: true
  26529. });
  26530. PostProcessRenderEffect.prototype._update = function () {
  26531. for (var renderPassName in this._renderPasses) {
  26532. this._renderPasses[renderPassName]._update();
  26533. }
  26534. };
  26535. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26536. this._renderPasses[renderPass._name] = renderPass;
  26537. this._linkParameters();
  26538. };
  26539. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26540. delete this._renderPasses[renderPass._name];
  26541. this._linkParameters();
  26542. };
  26543. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26544. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26545. this._linkParameters();
  26546. };
  26547. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26548. for (var renderPassName in this._renderPasses) {
  26549. if (renderPassName === passName) {
  26550. return this._renderPasses[passName];
  26551. }
  26552. }
  26553. };
  26554. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26555. this._renderPasses = {};
  26556. this._linkParameters();
  26557. };
  26558. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26559. var cameraKey;
  26560. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26561. for (var i = 0; i < _cam.length; i++) {
  26562. var camera = _cam[i];
  26563. var cameraName = camera.name;
  26564. if (this._singleInstance) {
  26565. cameraKey = 0;
  26566. }
  26567. else {
  26568. cameraKey = cameraName;
  26569. }
  26570. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26571. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26572. if (!this._indicesForCamera[cameraName]) {
  26573. this._indicesForCamera[cameraName] = [];
  26574. }
  26575. this._indicesForCamera[cameraName].push(index);
  26576. if (this._cameras.indexOf(camera) === -1) {
  26577. this._cameras[cameraName] = camera;
  26578. }
  26579. for (var passName in this._renderPasses) {
  26580. this._renderPasses[passName]._incRefCount();
  26581. }
  26582. }
  26583. this._linkParameters();
  26584. };
  26585. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26586. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26587. for (var i = 0; i < _cam.length; i++) {
  26588. var camera = _cam[i];
  26589. var cameraName = camera.name;
  26590. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26591. var index = this._cameras.indexOf(cameraName);
  26592. this._indicesForCamera.splice(index, 1);
  26593. this._cameras.splice(index, 1);
  26594. for (var passName in this._renderPasses) {
  26595. this._renderPasses[passName]._decRefCount();
  26596. }
  26597. }
  26598. };
  26599. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26600. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26601. for (var i = 0; i < _cam.length; i++) {
  26602. var camera = _cam[i];
  26603. var cameraName = camera.name;
  26604. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26605. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26606. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26607. }
  26608. }
  26609. for (var passName in this._renderPasses) {
  26610. this._renderPasses[passName]._incRefCount();
  26611. }
  26612. }
  26613. };
  26614. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26615. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26616. for (var i = 0; i < _cam.length; i++) {
  26617. var camera = _cam[i];
  26618. var cameraName = camera.Name;
  26619. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26620. for (var passName in this._renderPasses) {
  26621. this._renderPasses[passName]._decRefCount();
  26622. }
  26623. }
  26624. };
  26625. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26626. if (this._singleInstance) {
  26627. return this._postProcesses[0];
  26628. }
  26629. else {
  26630. return this._postProcesses[camera.name];
  26631. }
  26632. };
  26633. PostProcessRenderEffect.prototype._linkParameters = function () {
  26634. var _this = this;
  26635. for (var index in this._postProcesses) {
  26636. if (this.applyParameters) {
  26637. this.applyParameters(this._postProcesses[index]);
  26638. }
  26639. this._postProcesses[index].onBeforeRender = function (effect) {
  26640. _this._linkTextures(effect);
  26641. };
  26642. }
  26643. };
  26644. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26645. for (var renderPassName in this._renderPasses) {
  26646. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26647. }
  26648. for (var renderEffectName in this._renderEffectAsPasses) {
  26649. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26650. }
  26651. };
  26652. return PostProcessRenderEffect;
  26653. })();
  26654. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26655. })(BABYLON || (BABYLON = {}));
  26656. var BABYLON;
  26657. (function (BABYLON) {
  26658. var PostProcessRenderPipeline = (function () {
  26659. function PostProcessRenderPipeline(engine, name) {
  26660. this._engine = engine;
  26661. this._name = name;
  26662. this._renderEffects = {};
  26663. this._renderEffectsForIsolatedPass = {};
  26664. this._cameras = [];
  26665. }
  26666. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  26667. get: function () {
  26668. for (var renderEffectName in this._renderEffects) {
  26669. if (!this._renderEffects[renderEffectName].isSupported) {
  26670. return false;
  26671. }
  26672. }
  26673. return true;
  26674. },
  26675. enumerable: true,
  26676. configurable: true
  26677. });
  26678. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26679. this._renderEffects[renderEffect._name] = renderEffect;
  26680. };
  26681. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26682. var renderEffects = this._renderEffects[renderEffectName];
  26683. if (!renderEffects) {
  26684. return;
  26685. }
  26686. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26687. };
  26688. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26689. var renderEffects = this._renderEffects[renderEffectName];
  26690. if (!renderEffects) {
  26691. return;
  26692. }
  26693. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26694. };
  26695. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26696. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26697. var indicesToDelete = [];
  26698. var i;
  26699. for (i = 0; i < _cam.length; i++) {
  26700. var camera = _cam[i];
  26701. var cameraName = camera.name;
  26702. if (this._cameras.indexOf(camera) === -1) {
  26703. this._cameras[cameraName] = camera;
  26704. }
  26705. else if (unique) {
  26706. indicesToDelete.push(i);
  26707. }
  26708. }
  26709. for (i = 0; i < indicesToDelete.length; i++) {
  26710. cameras.splice(indicesToDelete[i], 1);
  26711. }
  26712. for (var renderEffectName in this._renderEffects) {
  26713. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26714. }
  26715. };
  26716. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26717. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26718. for (var renderEffectName in this._renderEffects) {
  26719. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26720. }
  26721. for (var i = 0; i < _cam.length; i++) {
  26722. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26723. }
  26724. };
  26725. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26726. var _this = this;
  26727. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26728. var pass = null;
  26729. var renderEffectName;
  26730. for (renderEffectName in this._renderEffects) {
  26731. pass = this._renderEffects[renderEffectName].getPass(passName);
  26732. if (pass != null) {
  26733. break;
  26734. }
  26735. }
  26736. if (pass === null) {
  26737. return;
  26738. }
  26739. for (renderEffectName in this._renderEffects) {
  26740. this._renderEffects[renderEffectName]._disable(_cam);
  26741. }
  26742. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26743. for (var i = 0; i < _cam.length; i++) {
  26744. var camera = _cam[i];
  26745. var cameraName = camera.name;
  26746. 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); });
  26747. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26748. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26749. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26750. }
  26751. };
  26752. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26753. var _this = this;
  26754. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26755. for (var i = 0; i < _cam.length; i++) {
  26756. var camera = _cam[i];
  26757. var cameraName = camera.name;
  26758. 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); });
  26759. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26760. }
  26761. for (var renderEffectName in this._renderEffects) {
  26762. this._renderEffects[renderEffectName]._enable(_cam);
  26763. }
  26764. };
  26765. PostProcessRenderPipeline.prototype._update = function () {
  26766. for (var renderEffectName in this._renderEffects) {
  26767. this._renderEffects[renderEffectName]._update();
  26768. }
  26769. for (var i = 0; i < this._cameras.length; i++) {
  26770. var cameraName = this._cameras[i].name;
  26771. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26772. this._renderEffectsForIsolatedPass[cameraName]._update();
  26773. }
  26774. }
  26775. };
  26776. PostProcessRenderPipeline.prototype.dispose = function () {
  26777. // Must be implemented by children
  26778. };
  26779. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26780. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26781. return PostProcessRenderPipeline;
  26782. })();
  26783. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26784. })(BABYLON || (BABYLON = {}));
  26785. var BABYLON;
  26786. (function (BABYLON) {
  26787. var PostProcessRenderPipelineManager = (function () {
  26788. function PostProcessRenderPipelineManager() {
  26789. this._renderPipelines = {};
  26790. }
  26791. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26792. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26793. };
  26794. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26795. var renderPipeline = this._renderPipelines[renderPipelineName];
  26796. if (!renderPipeline) {
  26797. return;
  26798. }
  26799. renderPipeline._attachCameras(cameras, unique);
  26800. };
  26801. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26802. var renderPipeline = this._renderPipelines[renderPipelineName];
  26803. if (!renderPipeline) {
  26804. return;
  26805. }
  26806. renderPipeline._detachCameras(cameras);
  26807. };
  26808. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26809. var renderPipeline = this._renderPipelines[renderPipelineName];
  26810. if (!renderPipeline) {
  26811. return;
  26812. }
  26813. renderPipeline._enableEffect(renderEffectName, cameras);
  26814. };
  26815. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26816. var renderPipeline = this._renderPipelines[renderPipelineName];
  26817. if (!renderPipeline) {
  26818. return;
  26819. }
  26820. renderPipeline._disableEffect(renderEffectName, cameras);
  26821. };
  26822. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26823. var renderPipeline = this._renderPipelines[renderPipelineName];
  26824. if (!renderPipeline) {
  26825. return;
  26826. }
  26827. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26828. };
  26829. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26830. var renderPipeline = this._renderPipelines[renderPipelineName];
  26831. if (!renderPipeline) {
  26832. return;
  26833. }
  26834. renderPipeline._disableDisplayOnlyPass(cameras);
  26835. };
  26836. PostProcessRenderPipelineManager.prototype.update = function () {
  26837. for (var renderPipelineName in this._renderPipelines) {
  26838. var pipeline = this._renderPipelines[renderPipelineName];
  26839. if (!pipeline.isSupported) {
  26840. pipeline.dispose();
  26841. delete this._renderPipelines[renderPipelineName];
  26842. }
  26843. else {
  26844. pipeline._update();
  26845. }
  26846. }
  26847. };
  26848. return PostProcessRenderPipelineManager;
  26849. })();
  26850. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26851. })(BABYLON || (BABYLON = {}));
  26852. var BABYLON;
  26853. (function (BABYLON) {
  26854. var BoundingBoxRenderer = (function () {
  26855. function BoundingBoxRenderer(scene) {
  26856. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26857. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26858. this.showBackLines = true;
  26859. this.renderList = new BABYLON.SmartArray(32);
  26860. this._scene = scene;
  26861. }
  26862. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26863. if (this._colorShader) {
  26864. return;
  26865. }
  26866. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26867. attributes: ["position"],
  26868. uniforms: ["worldViewProjection", "color"]
  26869. });
  26870. var engine = this._scene.getEngine();
  26871. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26872. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26873. 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]);
  26874. };
  26875. BoundingBoxRenderer.prototype.reset = function () {
  26876. this.renderList.reset();
  26877. };
  26878. BoundingBoxRenderer.prototype.render = function () {
  26879. if (this.renderList.length === 0) {
  26880. return;
  26881. }
  26882. this._prepareRessources();
  26883. if (!this._colorShader.isReady()) {
  26884. return;
  26885. }
  26886. var engine = this._scene.getEngine();
  26887. engine.setDepthWrite(false);
  26888. this._colorShader._preBind();
  26889. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26890. var boundingBox = this.renderList.data[boundingBoxIndex];
  26891. var min = boundingBox.minimum;
  26892. var max = boundingBox.maximum;
  26893. var diff = max.subtract(min);
  26894. var median = min.add(diff.scale(0.5));
  26895. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26896. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26897. .multiply(boundingBox.getWorldMatrix());
  26898. // VBOs
  26899. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26900. if (this.showBackLines) {
  26901. // Back
  26902. engine.setDepthFunctionToGreaterOrEqual();
  26903. this._scene.resetCachedMaterial();
  26904. this._colorShader.setColor4("color", this.backColor.toColor4());
  26905. this._colorShader.bind(worldMatrix);
  26906. // Draw order
  26907. engine.draw(false, 0, 24);
  26908. }
  26909. // Front
  26910. engine.setDepthFunctionToLess();
  26911. this._scene.resetCachedMaterial();
  26912. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26913. this._colorShader.bind(worldMatrix);
  26914. // Draw order
  26915. engine.draw(false, 0, 24);
  26916. }
  26917. this._colorShader.unbind();
  26918. engine.setDepthFunctionToLessOrEqual();
  26919. engine.setDepthWrite(true);
  26920. };
  26921. BoundingBoxRenderer.prototype.dispose = function () {
  26922. if (!this._colorShader) {
  26923. return;
  26924. }
  26925. this._colorShader.dispose();
  26926. this._vb.dispose();
  26927. this._scene.getEngine()._releaseBuffer(this._ib);
  26928. };
  26929. return BoundingBoxRenderer;
  26930. })();
  26931. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26932. })(BABYLON || (BABYLON = {}));
  26933. var BABYLON;
  26934. (function (BABYLON) {
  26935. var Condition = (function () {
  26936. function Condition(actionManager) {
  26937. this._actionManager = actionManager;
  26938. }
  26939. Condition.prototype.isValid = function () {
  26940. return true;
  26941. };
  26942. Condition.prototype._getProperty = function (propertyPath) {
  26943. return this._actionManager._getProperty(propertyPath);
  26944. };
  26945. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26946. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26947. };
  26948. return Condition;
  26949. })();
  26950. BABYLON.Condition = Condition;
  26951. var ValueCondition = (function (_super) {
  26952. __extends(ValueCondition, _super);
  26953. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26954. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26955. _super.call(this, actionManager);
  26956. this.propertyPath = propertyPath;
  26957. this.value = value;
  26958. this.operator = operator;
  26959. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26960. this._property = this._getProperty(this.propertyPath);
  26961. }
  26962. Object.defineProperty(ValueCondition, "IsEqual", {
  26963. get: function () {
  26964. return ValueCondition._IsEqual;
  26965. },
  26966. enumerable: true,
  26967. configurable: true
  26968. });
  26969. Object.defineProperty(ValueCondition, "IsDifferent", {
  26970. get: function () {
  26971. return ValueCondition._IsDifferent;
  26972. },
  26973. enumerable: true,
  26974. configurable: true
  26975. });
  26976. Object.defineProperty(ValueCondition, "IsGreater", {
  26977. get: function () {
  26978. return ValueCondition._IsGreater;
  26979. },
  26980. enumerable: true,
  26981. configurable: true
  26982. });
  26983. Object.defineProperty(ValueCondition, "IsLesser", {
  26984. get: function () {
  26985. return ValueCondition._IsLesser;
  26986. },
  26987. enumerable: true,
  26988. configurable: true
  26989. });
  26990. // Methods
  26991. ValueCondition.prototype.isValid = function () {
  26992. switch (this.operator) {
  26993. case ValueCondition.IsGreater:
  26994. return this._target[this._property] > this.value;
  26995. case ValueCondition.IsLesser:
  26996. return this._target[this._property] < this.value;
  26997. case ValueCondition.IsEqual:
  26998. case ValueCondition.IsDifferent:
  26999. var check;
  27000. if (this.value.equals) {
  27001. check = this.value.equals(this._target[this._property]);
  27002. }
  27003. else {
  27004. check = this.value === this._target[this._property];
  27005. }
  27006. return this.operator === ValueCondition.IsEqual ? check : !check;
  27007. }
  27008. return false;
  27009. };
  27010. // Statics
  27011. ValueCondition._IsEqual = 0;
  27012. ValueCondition._IsDifferent = 1;
  27013. ValueCondition._IsGreater = 2;
  27014. ValueCondition._IsLesser = 3;
  27015. return ValueCondition;
  27016. })(Condition);
  27017. BABYLON.ValueCondition = ValueCondition;
  27018. var PredicateCondition = (function (_super) {
  27019. __extends(PredicateCondition, _super);
  27020. function PredicateCondition(actionManager, predicate) {
  27021. _super.call(this, actionManager);
  27022. this.predicate = predicate;
  27023. }
  27024. PredicateCondition.prototype.isValid = function () {
  27025. return this.predicate();
  27026. };
  27027. return PredicateCondition;
  27028. })(Condition);
  27029. BABYLON.PredicateCondition = PredicateCondition;
  27030. var StateCondition = (function (_super) {
  27031. __extends(StateCondition, _super);
  27032. function StateCondition(actionManager, target, value) {
  27033. _super.call(this, actionManager);
  27034. this.value = value;
  27035. this._target = target;
  27036. }
  27037. // Methods
  27038. StateCondition.prototype.isValid = function () {
  27039. return this._target.state === this.value;
  27040. };
  27041. return StateCondition;
  27042. })(Condition);
  27043. BABYLON.StateCondition = StateCondition;
  27044. })(BABYLON || (BABYLON = {}));
  27045. var BABYLON;
  27046. (function (BABYLON) {
  27047. var Action = (function () {
  27048. function Action(triggerOptions, condition) {
  27049. this.triggerOptions = triggerOptions;
  27050. if (triggerOptions.parameter) {
  27051. this.trigger = triggerOptions.trigger;
  27052. this._triggerParameter = triggerOptions.parameter;
  27053. }
  27054. else {
  27055. this.trigger = triggerOptions;
  27056. }
  27057. this._nextActiveAction = this;
  27058. this._condition = condition;
  27059. }
  27060. // Methods
  27061. Action.prototype._prepare = function () {
  27062. };
  27063. Action.prototype.getTriggerParameter = function () {
  27064. return this._triggerParameter;
  27065. };
  27066. Action.prototype._executeCurrent = function (evt) {
  27067. if (this._nextActiveAction._condition) {
  27068. var condition = this._nextActiveAction._condition;
  27069. var currentRenderId = this._actionManager.getScene().getRenderId();
  27070. // We cache the current evaluation for the current frame
  27071. if (condition._evaluationId === currentRenderId) {
  27072. if (!condition._currentResult) {
  27073. return;
  27074. }
  27075. }
  27076. else {
  27077. condition._evaluationId = currentRenderId;
  27078. if (!condition.isValid()) {
  27079. condition._currentResult = false;
  27080. return;
  27081. }
  27082. condition._currentResult = true;
  27083. }
  27084. }
  27085. this._nextActiveAction.execute(evt);
  27086. this.skipToNextActiveAction();
  27087. };
  27088. Action.prototype.execute = function (evt) {
  27089. };
  27090. Action.prototype.skipToNextActiveAction = function () {
  27091. if (this._nextActiveAction._child) {
  27092. if (!this._nextActiveAction._child._actionManager) {
  27093. this._nextActiveAction._child._actionManager = this._actionManager;
  27094. }
  27095. this._nextActiveAction = this._nextActiveAction._child;
  27096. }
  27097. else {
  27098. this._nextActiveAction = this;
  27099. }
  27100. };
  27101. Action.prototype.then = function (action) {
  27102. this._child = action;
  27103. action._actionManager = this._actionManager;
  27104. action._prepare();
  27105. return action;
  27106. };
  27107. Action.prototype._getProperty = function (propertyPath) {
  27108. return this._actionManager._getProperty(propertyPath);
  27109. };
  27110. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27111. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27112. };
  27113. return Action;
  27114. })();
  27115. BABYLON.Action = Action;
  27116. })(BABYLON || (BABYLON = {}));
  27117. var BABYLON;
  27118. (function (BABYLON) {
  27119. /**
  27120. * ActionEvent is the event beint sent when an action is triggered.
  27121. */
  27122. var ActionEvent = (function () {
  27123. /**
  27124. * @constructor
  27125. * @param source The mesh or sprite that triggered the action.
  27126. * @param pointerX The X mouse cursor position at the time of the event
  27127. * @param pointerY The Y mouse cursor position at the time of the event
  27128. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27129. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27130. */
  27131. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27132. this.source = source;
  27133. this.pointerX = pointerX;
  27134. this.pointerY = pointerY;
  27135. this.meshUnderPointer = meshUnderPointer;
  27136. this.sourceEvent = sourceEvent;
  27137. this.additionalData = additionalData;
  27138. }
  27139. /**
  27140. * Helper function to auto-create an ActionEvent from a source mesh.
  27141. * @param source The source mesh that triggered the event
  27142. * @param evt {Event} The original (browser) event
  27143. */
  27144. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27145. var scene = source.getScene();
  27146. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27147. };
  27148. /**
  27149. * Helper function to auto-create an ActionEvent from a source mesh.
  27150. * @param source The source sprite that triggered the event
  27151. * @param scene Scene associated with the sprite
  27152. * @param evt {Event} The original (browser) event
  27153. */
  27154. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  27155. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27156. };
  27157. /**
  27158. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27159. * @param scene the scene where the event occurred
  27160. * @param evt {Event} The original (browser) event
  27161. */
  27162. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27163. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27164. };
  27165. return ActionEvent;
  27166. })();
  27167. BABYLON.ActionEvent = ActionEvent;
  27168. /**
  27169. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27170. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27171. */
  27172. var ActionManager = (function () {
  27173. function ActionManager(scene) {
  27174. // Members
  27175. this.actions = new Array();
  27176. this._scene = scene;
  27177. scene._actionManagers.push(this);
  27178. }
  27179. Object.defineProperty(ActionManager, "NothingTrigger", {
  27180. get: function () {
  27181. return ActionManager._NothingTrigger;
  27182. },
  27183. enumerable: true,
  27184. configurable: true
  27185. });
  27186. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27187. get: function () {
  27188. return ActionManager._OnPickTrigger;
  27189. },
  27190. enumerable: true,
  27191. configurable: true
  27192. });
  27193. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27194. get: function () {
  27195. return ActionManager._OnLeftPickTrigger;
  27196. },
  27197. enumerable: true,
  27198. configurable: true
  27199. });
  27200. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27201. get: function () {
  27202. return ActionManager._OnRightPickTrigger;
  27203. },
  27204. enumerable: true,
  27205. configurable: true
  27206. });
  27207. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27208. get: function () {
  27209. return ActionManager._OnCenterPickTrigger;
  27210. },
  27211. enumerable: true,
  27212. configurable: true
  27213. });
  27214. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  27215. get: function () {
  27216. return ActionManager._OnPickDownTrigger;
  27217. },
  27218. enumerable: true,
  27219. configurable: true
  27220. });
  27221. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27222. get: function () {
  27223. return ActionManager._OnPickUpTrigger;
  27224. },
  27225. enumerable: true,
  27226. configurable: true
  27227. });
  27228. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  27229. /// This trigger will only be raised if you also declared a OnPickDown
  27230. get: function () {
  27231. return ActionManager._OnPickOutTrigger;
  27232. },
  27233. enumerable: true,
  27234. configurable: true
  27235. });
  27236. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  27237. get: function () {
  27238. return ActionManager._OnLongPressTrigger;
  27239. },
  27240. enumerable: true,
  27241. configurable: true
  27242. });
  27243. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27244. get: function () {
  27245. return ActionManager._OnPointerOverTrigger;
  27246. },
  27247. enumerable: true,
  27248. configurable: true
  27249. });
  27250. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27251. get: function () {
  27252. return ActionManager._OnPointerOutTrigger;
  27253. },
  27254. enumerable: true,
  27255. configurable: true
  27256. });
  27257. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27258. get: function () {
  27259. return ActionManager._OnEveryFrameTrigger;
  27260. },
  27261. enumerable: true,
  27262. configurable: true
  27263. });
  27264. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27265. get: function () {
  27266. return ActionManager._OnIntersectionEnterTrigger;
  27267. },
  27268. enumerable: true,
  27269. configurable: true
  27270. });
  27271. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27272. get: function () {
  27273. return ActionManager._OnIntersectionExitTrigger;
  27274. },
  27275. enumerable: true,
  27276. configurable: true
  27277. });
  27278. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27279. get: function () {
  27280. return ActionManager._OnKeyDownTrigger;
  27281. },
  27282. enumerable: true,
  27283. configurable: true
  27284. });
  27285. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27286. get: function () {
  27287. return ActionManager._OnKeyUpTrigger;
  27288. },
  27289. enumerable: true,
  27290. configurable: true
  27291. });
  27292. // Methods
  27293. ActionManager.prototype.dispose = function () {
  27294. var index = this._scene._actionManagers.indexOf(this);
  27295. if (index > -1) {
  27296. this._scene._actionManagers.splice(index, 1);
  27297. }
  27298. };
  27299. ActionManager.prototype.getScene = function () {
  27300. return this._scene;
  27301. };
  27302. /**
  27303. * Does this action manager handles actions of any of the given triggers
  27304. * @param {number[]} triggers - the triggers to be tested
  27305. * @return {boolean} whether one (or more) of the triggers is handeled
  27306. */
  27307. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27308. for (var index = 0; index < this.actions.length; index++) {
  27309. var action = this.actions[index];
  27310. if (triggers.indexOf(action.trigger) > -1) {
  27311. return true;
  27312. }
  27313. }
  27314. return false;
  27315. };
  27316. /**
  27317. * Does this action manager handles actions of a given trigger
  27318. * @param {number} trigger - the trigger to be tested
  27319. * @return {boolean} whether the trigger is handeled
  27320. */
  27321. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27322. for (var index = 0; index < this.actions.length; index++) {
  27323. var action = this.actions[index];
  27324. if (action.trigger === trigger) {
  27325. return true;
  27326. }
  27327. }
  27328. return false;
  27329. };
  27330. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27331. /**
  27332. * Does this action manager has pointer triggers
  27333. * @return {boolean} whether or not it has pointer triggers
  27334. */
  27335. get: function () {
  27336. for (var index = 0; index < this.actions.length; index++) {
  27337. var action = this.actions[index];
  27338. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27339. return true;
  27340. }
  27341. }
  27342. return false;
  27343. },
  27344. enumerable: true,
  27345. configurable: true
  27346. });
  27347. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27348. /**
  27349. * Does this action manager has pick triggers
  27350. * @return {boolean} whether or not it has pick triggers
  27351. */
  27352. get: function () {
  27353. for (var index = 0; index < this.actions.length; index++) {
  27354. var action = this.actions[index];
  27355. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  27356. return true;
  27357. }
  27358. }
  27359. return false;
  27360. },
  27361. enumerable: true,
  27362. configurable: true
  27363. });
  27364. /**
  27365. * Registers an action to this action manager
  27366. * @param {BABYLON.Action} action - the action to be registered
  27367. * @return {BABYLON.Action} the action amended (prepared) after registration
  27368. */
  27369. ActionManager.prototype.registerAction = function (action) {
  27370. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27371. if (this.getScene().actionManager !== this) {
  27372. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27373. return null;
  27374. }
  27375. }
  27376. this.actions.push(action);
  27377. action._actionManager = this;
  27378. action._prepare();
  27379. return action;
  27380. };
  27381. /**
  27382. * Process a specific trigger
  27383. * @param {number} trigger - the trigger to process
  27384. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27385. */
  27386. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27387. for (var index = 0; index < this.actions.length; index++) {
  27388. var action = this.actions[index];
  27389. if (action.trigger === trigger) {
  27390. if (trigger === ActionManager.OnKeyUpTrigger
  27391. || trigger === ActionManager.OnKeyDownTrigger) {
  27392. var parameter = action.getTriggerParameter();
  27393. if (parameter) {
  27394. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27395. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27396. if (actualkey !== parameter.toLowerCase()) {
  27397. continue;
  27398. }
  27399. }
  27400. }
  27401. action._executeCurrent(evt);
  27402. }
  27403. }
  27404. };
  27405. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27406. var properties = propertyPath.split(".");
  27407. for (var index = 0; index < properties.length - 1; index++) {
  27408. target = target[properties[index]];
  27409. }
  27410. return target;
  27411. };
  27412. ActionManager.prototype._getProperty = function (propertyPath) {
  27413. var properties = propertyPath.split(".");
  27414. return properties[properties.length - 1];
  27415. };
  27416. ActionManager.Parse = function (parsedActions, object, scene) {
  27417. var actionManager = new BABYLON.ActionManager(scene);
  27418. if (object === null)
  27419. scene.actionManager = actionManager;
  27420. else
  27421. object.actionManager = actionManager;
  27422. // instanciate a new object
  27423. var instanciate = function (name, params) {
  27424. var newInstance = Object.create(BABYLON[name].prototype);
  27425. newInstance.constructor.apply(newInstance, params);
  27426. return newInstance;
  27427. };
  27428. var parseParameter = function (name, value, target, propertyPath) {
  27429. if (propertyPath === null) {
  27430. // String, boolean or float
  27431. var floatValue = parseFloat(value);
  27432. if (value === "true" || value === "false")
  27433. return value === "true";
  27434. else
  27435. return isNaN(floatValue) ? value : floatValue;
  27436. }
  27437. var effectiveTarget = propertyPath.split(".");
  27438. var values = value.split(",");
  27439. // Get effective Target
  27440. for (var i = 0; i < effectiveTarget.length; i++) {
  27441. target = target[effectiveTarget[i]];
  27442. }
  27443. // Return appropriate value with its type
  27444. if (typeof (target) === "boolean")
  27445. return values[0] === "true";
  27446. if (typeof (target) === "string")
  27447. return values[0];
  27448. // Parameters with multiple values such as Vector3 etc.
  27449. var split = new Array();
  27450. for (var i = 0; i < values.length; i++)
  27451. split.push(parseFloat(values[i]));
  27452. if (target instanceof BABYLON.Vector3)
  27453. return BABYLON.Vector3.FromArray(split);
  27454. if (target instanceof BABYLON.Vector4)
  27455. return BABYLON.Vector4.FromArray(split);
  27456. if (target instanceof BABYLON.Color3)
  27457. return BABYLON.Color3.FromArray(split);
  27458. if (target instanceof BABYLON.Color4)
  27459. return BABYLON.Color4.FromArray(split);
  27460. return parseFloat(values[0]);
  27461. };
  27462. // traverse graph per trigger
  27463. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  27464. if (combineArray === void 0) { combineArray = null; }
  27465. if (parsedAction.detached)
  27466. return;
  27467. var parameters = new Array();
  27468. var target = null;
  27469. var propertyPath = null;
  27470. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  27471. // Parameters
  27472. if (parsedAction.type === 2)
  27473. parameters.push(actionManager);
  27474. else
  27475. parameters.push(trigger);
  27476. if (combine) {
  27477. var actions = new Array();
  27478. for (var j = 0; j < parsedAction.combine.length; j++) {
  27479. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  27480. }
  27481. parameters.push(actions);
  27482. }
  27483. else {
  27484. for (var i = 0; i < parsedAction.properties.length; i++) {
  27485. var value = parsedAction.properties[i].value;
  27486. var name = parsedAction.properties[i].name;
  27487. var targetType = parsedAction.properties[i].targetType;
  27488. if (name === "target")
  27489. if (targetType !== null && targetType === "SceneProperties")
  27490. value = target = scene;
  27491. else
  27492. value = target = scene.getNodeByName(value);
  27493. else if (name === "parent")
  27494. value = scene.getNodeByName(value);
  27495. else if (name === "sound")
  27496. value = scene.getSoundByName(value);
  27497. else if (name !== "propertyPath") {
  27498. if (parsedAction.type === 2 && name === "operator")
  27499. value = BABYLON.ValueCondition[value];
  27500. else
  27501. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  27502. }
  27503. else {
  27504. propertyPath = value;
  27505. }
  27506. parameters.push(value);
  27507. }
  27508. }
  27509. if (combineArray === null) {
  27510. parameters.push(condition);
  27511. }
  27512. else {
  27513. parameters.push(null);
  27514. }
  27515. // If interpolate value action
  27516. if (parsedAction.name === "InterpolateValueAction") {
  27517. var param = parameters[parameters.length - 2];
  27518. parameters[parameters.length - 1] = param;
  27519. parameters[parameters.length - 2] = condition;
  27520. }
  27521. // Action or condition(s) and not CombineAction
  27522. var newAction = instanciate(parsedAction.name, parameters);
  27523. if (newAction instanceof BABYLON.Condition && condition !== null) {
  27524. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  27525. if (action)
  27526. action.then(nothing);
  27527. else
  27528. actionManager.registerAction(nothing);
  27529. action = nothing;
  27530. }
  27531. if (combineArray === null) {
  27532. if (newAction instanceof BABYLON.Condition) {
  27533. condition = newAction;
  27534. newAction = action;
  27535. }
  27536. else {
  27537. condition = null;
  27538. if (action)
  27539. action.then(newAction);
  27540. else
  27541. actionManager.registerAction(newAction);
  27542. }
  27543. }
  27544. else {
  27545. combineArray.push(newAction);
  27546. }
  27547. for (var i = 0; i < parsedAction.children.length; i++)
  27548. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  27549. };
  27550. // triggers
  27551. for (var i = 0; i < parsedActions.children.length; i++) {
  27552. var triggerParams;
  27553. var trigger = parsedActions.children[i];
  27554. if (trigger.properties.length > 0) {
  27555. var param = trigger.properties[0].value;
  27556. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  27557. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  27558. }
  27559. else
  27560. triggerParams = BABYLON.ActionManager[trigger.name];
  27561. for (var j = 0; j < trigger.children.length; j++) {
  27562. if (!trigger.detached)
  27563. traverse(trigger.children[j], triggerParams, null, null);
  27564. }
  27565. }
  27566. };
  27567. // Statics
  27568. ActionManager._NothingTrigger = 0;
  27569. ActionManager._OnPickTrigger = 1;
  27570. ActionManager._OnLeftPickTrigger = 2;
  27571. ActionManager._OnRightPickTrigger = 3;
  27572. ActionManager._OnCenterPickTrigger = 4;
  27573. ActionManager._OnPickDownTrigger = 5;
  27574. ActionManager._OnPickUpTrigger = 6;
  27575. ActionManager._OnLongPressTrigger = 7;
  27576. ActionManager._OnPointerOverTrigger = 8;
  27577. ActionManager._OnPointerOutTrigger = 9;
  27578. ActionManager._OnEveryFrameTrigger = 10;
  27579. ActionManager._OnIntersectionEnterTrigger = 11;
  27580. ActionManager._OnIntersectionExitTrigger = 12;
  27581. ActionManager._OnKeyDownTrigger = 13;
  27582. ActionManager._OnKeyUpTrigger = 14;
  27583. ActionManager._OnPickOutTrigger = 15;
  27584. ActionManager.DragMovementThreshold = 10; // in pixels
  27585. ActionManager.LongPressDelay = 500; // in milliseconds
  27586. return ActionManager;
  27587. })();
  27588. BABYLON.ActionManager = ActionManager;
  27589. })(BABYLON || (BABYLON = {}));
  27590. var BABYLON;
  27591. (function (BABYLON) {
  27592. var InterpolateValueAction = (function (_super) {
  27593. __extends(InterpolateValueAction, _super);
  27594. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  27595. if (duration === void 0) { duration = 1000; }
  27596. _super.call(this, triggerOptions, condition);
  27597. this.propertyPath = propertyPath;
  27598. this.value = value;
  27599. this.duration = duration;
  27600. this.stopOtherAnimations = stopOtherAnimations;
  27601. this.onInterpolationDone = onInterpolationDone;
  27602. this._target = target;
  27603. }
  27604. InterpolateValueAction.prototype._prepare = function () {
  27605. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27606. this._property = this._getProperty(this.propertyPath);
  27607. };
  27608. InterpolateValueAction.prototype.execute = function () {
  27609. var scene = this._actionManager.getScene();
  27610. var keys = [
  27611. {
  27612. frame: 0,
  27613. value: this._target[this._property]
  27614. }, {
  27615. frame: 100,
  27616. value: this.value
  27617. }
  27618. ];
  27619. var dataType;
  27620. if (typeof this.value === "number") {
  27621. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27622. }
  27623. else if (this.value instanceof BABYLON.Color3) {
  27624. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27625. }
  27626. else if (this.value instanceof BABYLON.Vector3) {
  27627. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27628. }
  27629. else if (this.value instanceof BABYLON.Matrix) {
  27630. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27631. }
  27632. else if (this.value instanceof BABYLON.Quaternion) {
  27633. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27634. }
  27635. else {
  27636. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27637. return;
  27638. }
  27639. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27640. animation.setKeys(keys);
  27641. if (this.stopOtherAnimations) {
  27642. scene.stopAnimation(this._target);
  27643. }
  27644. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  27645. };
  27646. return InterpolateValueAction;
  27647. })(BABYLON.Action);
  27648. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27649. })(BABYLON || (BABYLON = {}));
  27650. var BABYLON;
  27651. (function (BABYLON) {
  27652. var SwitchBooleanAction = (function (_super) {
  27653. __extends(SwitchBooleanAction, _super);
  27654. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27655. _super.call(this, triggerOptions, condition);
  27656. this.propertyPath = propertyPath;
  27657. this._target = target;
  27658. }
  27659. SwitchBooleanAction.prototype._prepare = function () {
  27660. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27661. this._property = this._getProperty(this.propertyPath);
  27662. };
  27663. SwitchBooleanAction.prototype.execute = function () {
  27664. this._target[this._property] = !this._target[this._property];
  27665. };
  27666. return SwitchBooleanAction;
  27667. })(BABYLON.Action);
  27668. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27669. var SetStateAction = (function (_super) {
  27670. __extends(SetStateAction, _super);
  27671. function SetStateAction(triggerOptions, target, value, condition) {
  27672. _super.call(this, triggerOptions, condition);
  27673. this.value = value;
  27674. this._target = target;
  27675. }
  27676. SetStateAction.prototype.execute = function () {
  27677. this._target.state = this.value;
  27678. };
  27679. return SetStateAction;
  27680. })(BABYLON.Action);
  27681. BABYLON.SetStateAction = SetStateAction;
  27682. var SetValueAction = (function (_super) {
  27683. __extends(SetValueAction, _super);
  27684. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27685. _super.call(this, triggerOptions, condition);
  27686. this.propertyPath = propertyPath;
  27687. this.value = value;
  27688. this._target = target;
  27689. }
  27690. SetValueAction.prototype._prepare = function () {
  27691. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27692. this._property = this._getProperty(this.propertyPath);
  27693. };
  27694. SetValueAction.prototype.execute = function () {
  27695. this._target[this._property] = this.value;
  27696. };
  27697. return SetValueAction;
  27698. })(BABYLON.Action);
  27699. BABYLON.SetValueAction = SetValueAction;
  27700. var IncrementValueAction = (function (_super) {
  27701. __extends(IncrementValueAction, _super);
  27702. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27703. _super.call(this, triggerOptions, condition);
  27704. this.propertyPath = propertyPath;
  27705. this.value = value;
  27706. this._target = target;
  27707. }
  27708. IncrementValueAction.prototype._prepare = function () {
  27709. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27710. this._property = this._getProperty(this.propertyPath);
  27711. if (typeof this._target[this._property] !== "number") {
  27712. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27713. }
  27714. };
  27715. IncrementValueAction.prototype.execute = function () {
  27716. this._target[this._property] += this.value;
  27717. };
  27718. return IncrementValueAction;
  27719. })(BABYLON.Action);
  27720. BABYLON.IncrementValueAction = IncrementValueAction;
  27721. var PlayAnimationAction = (function (_super) {
  27722. __extends(PlayAnimationAction, _super);
  27723. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27724. _super.call(this, triggerOptions, condition);
  27725. this.from = from;
  27726. this.to = to;
  27727. this.loop = loop;
  27728. this._target = target;
  27729. }
  27730. PlayAnimationAction.prototype._prepare = function () {
  27731. };
  27732. PlayAnimationAction.prototype.execute = function () {
  27733. var scene = this._actionManager.getScene();
  27734. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27735. };
  27736. return PlayAnimationAction;
  27737. })(BABYLON.Action);
  27738. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27739. var StopAnimationAction = (function (_super) {
  27740. __extends(StopAnimationAction, _super);
  27741. function StopAnimationAction(triggerOptions, target, condition) {
  27742. _super.call(this, triggerOptions, condition);
  27743. this._target = target;
  27744. }
  27745. StopAnimationAction.prototype._prepare = function () {
  27746. };
  27747. StopAnimationAction.prototype.execute = function () {
  27748. var scene = this._actionManager.getScene();
  27749. scene.stopAnimation(this._target);
  27750. };
  27751. return StopAnimationAction;
  27752. })(BABYLON.Action);
  27753. BABYLON.StopAnimationAction = StopAnimationAction;
  27754. var DoNothingAction = (function (_super) {
  27755. __extends(DoNothingAction, _super);
  27756. function DoNothingAction(triggerOptions, condition) {
  27757. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27758. _super.call(this, triggerOptions, condition);
  27759. }
  27760. DoNothingAction.prototype.execute = function () {
  27761. };
  27762. return DoNothingAction;
  27763. })(BABYLON.Action);
  27764. BABYLON.DoNothingAction = DoNothingAction;
  27765. var CombineAction = (function (_super) {
  27766. __extends(CombineAction, _super);
  27767. function CombineAction(triggerOptions, children, condition) {
  27768. _super.call(this, triggerOptions, condition);
  27769. this.children = children;
  27770. }
  27771. CombineAction.prototype._prepare = function () {
  27772. for (var index = 0; index < this.children.length; index++) {
  27773. this.children[index]._actionManager = this._actionManager;
  27774. this.children[index]._prepare();
  27775. }
  27776. };
  27777. CombineAction.prototype.execute = function (evt) {
  27778. for (var index = 0; index < this.children.length; index++) {
  27779. this.children[index].execute(evt);
  27780. }
  27781. };
  27782. return CombineAction;
  27783. })(BABYLON.Action);
  27784. BABYLON.CombineAction = CombineAction;
  27785. var ExecuteCodeAction = (function (_super) {
  27786. __extends(ExecuteCodeAction, _super);
  27787. function ExecuteCodeAction(triggerOptions, func, condition) {
  27788. _super.call(this, triggerOptions, condition);
  27789. this.func = func;
  27790. }
  27791. ExecuteCodeAction.prototype.execute = function (evt) {
  27792. this.func(evt);
  27793. };
  27794. return ExecuteCodeAction;
  27795. })(BABYLON.Action);
  27796. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27797. var SetParentAction = (function (_super) {
  27798. __extends(SetParentAction, _super);
  27799. function SetParentAction(triggerOptions, target, parent, condition) {
  27800. _super.call(this, triggerOptions, condition);
  27801. this._target = target;
  27802. this._parent = parent;
  27803. }
  27804. SetParentAction.prototype._prepare = function () {
  27805. };
  27806. SetParentAction.prototype.execute = function () {
  27807. if (this._target.parent === this._parent) {
  27808. return;
  27809. }
  27810. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27811. invertParentWorldMatrix.invert();
  27812. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27813. this._target.parent = this._parent;
  27814. };
  27815. return SetParentAction;
  27816. })(BABYLON.Action);
  27817. BABYLON.SetParentAction = SetParentAction;
  27818. var PlaySoundAction = (function (_super) {
  27819. __extends(PlaySoundAction, _super);
  27820. function PlaySoundAction(triggerOptions, sound, condition) {
  27821. _super.call(this, triggerOptions, condition);
  27822. this._sound = sound;
  27823. }
  27824. PlaySoundAction.prototype._prepare = function () {
  27825. };
  27826. PlaySoundAction.prototype.execute = function () {
  27827. if (this._sound !== undefined)
  27828. this._sound.play();
  27829. };
  27830. return PlaySoundAction;
  27831. })(BABYLON.Action);
  27832. BABYLON.PlaySoundAction = PlaySoundAction;
  27833. var StopSoundAction = (function (_super) {
  27834. __extends(StopSoundAction, _super);
  27835. function StopSoundAction(triggerOptions, sound, condition) {
  27836. _super.call(this, triggerOptions, condition);
  27837. this._sound = sound;
  27838. }
  27839. StopSoundAction.prototype._prepare = function () {
  27840. };
  27841. StopSoundAction.prototype.execute = function () {
  27842. if (this._sound !== undefined)
  27843. this._sound.stop();
  27844. };
  27845. return StopSoundAction;
  27846. })(BABYLON.Action);
  27847. BABYLON.StopSoundAction = StopSoundAction;
  27848. })(BABYLON || (BABYLON = {}));
  27849. var BABYLON;
  27850. (function (BABYLON) {
  27851. var Geometry = (function () {
  27852. function Geometry(id, scene, vertexData, updatable, mesh) {
  27853. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27854. this._totalVertices = 0;
  27855. this._isDisposed = false;
  27856. this.id = id;
  27857. this._engine = scene.getEngine();
  27858. this._meshes = [];
  27859. this._scene = scene;
  27860. //Init vertex buffer cache
  27861. this._vertexBuffers = {};
  27862. this._indices = [];
  27863. // vertexData
  27864. if (vertexData) {
  27865. this.setAllVerticesData(vertexData, updatable);
  27866. }
  27867. else {
  27868. this._totalVertices = 0;
  27869. this._indices = [];
  27870. }
  27871. // applyToMesh
  27872. if (mesh) {
  27873. this.applyToMesh(mesh);
  27874. mesh.computeWorldMatrix(true);
  27875. }
  27876. }
  27877. Object.defineProperty(Geometry.prototype, "extend", {
  27878. get: function () {
  27879. return this._extend;
  27880. },
  27881. enumerable: true,
  27882. configurable: true
  27883. });
  27884. Geometry.prototype.getScene = function () {
  27885. return this._scene;
  27886. };
  27887. Geometry.prototype.getEngine = function () {
  27888. return this._engine;
  27889. };
  27890. Geometry.prototype.isReady = function () {
  27891. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27892. };
  27893. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27894. vertexData.applyToGeometry(this, updatable);
  27895. this.notifyUpdate();
  27896. };
  27897. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27898. if (this._vertexBuffers[kind]) {
  27899. this._vertexBuffers[kind].dispose();
  27900. }
  27901. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27902. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27903. stride = this._vertexBuffers[kind].getStrideSize();
  27904. this._totalVertices = data.length / stride;
  27905. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27906. var meshes = this._meshes;
  27907. var numOfMeshes = meshes.length;
  27908. for (var index = 0; index < numOfMeshes; index++) {
  27909. var mesh = meshes[index];
  27910. mesh._resetPointsArrayCache();
  27911. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27912. mesh._createGlobalSubMesh();
  27913. mesh.computeWorldMatrix(true);
  27914. }
  27915. }
  27916. this.notifyUpdate(kind);
  27917. };
  27918. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27919. var vertexBuffer = this.getVertexBuffer(kind);
  27920. if (!vertexBuffer) {
  27921. return;
  27922. }
  27923. vertexBuffer.updateDirectly(data, offset);
  27924. this.notifyUpdate(kind);
  27925. };
  27926. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27927. var vertexBuffer = this.getVertexBuffer(kind);
  27928. if (!vertexBuffer) {
  27929. return;
  27930. }
  27931. vertexBuffer.update(data);
  27932. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27933. var stride = vertexBuffer.getStrideSize();
  27934. this._totalVertices = data.length / stride;
  27935. if (updateExtends) {
  27936. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27937. }
  27938. var meshes = this._meshes;
  27939. var numOfMeshes = meshes.length;
  27940. for (var index = 0; index < numOfMeshes; index++) {
  27941. var mesh = meshes[index];
  27942. mesh._resetPointsArrayCache();
  27943. if (updateExtends) {
  27944. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27945. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27946. var subMesh = mesh.subMeshes[subIndex];
  27947. subMesh.refreshBoundingInfo();
  27948. }
  27949. }
  27950. }
  27951. }
  27952. this.notifyUpdate(kind);
  27953. };
  27954. Geometry.prototype.getTotalVertices = function () {
  27955. if (!this.isReady()) {
  27956. return 0;
  27957. }
  27958. return this._totalVertices;
  27959. };
  27960. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27961. var vertexBuffer = this.getVertexBuffer(kind);
  27962. if (!vertexBuffer) {
  27963. return null;
  27964. }
  27965. var orig = vertexBuffer.getData();
  27966. if (!copyWhenShared || this._meshes.length === 1) {
  27967. return orig;
  27968. }
  27969. else {
  27970. var len = orig.length;
  27971. var copy = [];
  27972. for (var i = 0; i < len; i++) {
  27973. copy.push(orig[i]);
  27974. }
  27975. return copy;
  27976. }
  27977. };
  27978. Geometry.prototype.getVertexBuffer = function (kind) {
  27979. if (!this.isReady()) {
  27980. return null;
  27981. }
  27982. return this._vertexBuffers[kind];
  27983. };
  27984. Geometry.prototype.getVertexBuffers = function () {
  27985. if (!this.isReady()) {
  27986. return null;
  27987. }
  27988. return this._vertexBuffers;
  27989. };
  27990. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27991. if (!this._vertexBuffers) {
  27992. if (this._delayInfo) {
  27993. return this._delayInfo.indexOf(kind) !== -1;
  27994. }
  27995. return false;
  27996. }
  27997. return this._vertexBuffers[kind] !== undefined;
  27998. };
  27999. Geometry.prototype.getVerticesDataKinds = function () {
  28000. var result = [];
  28001. var kind;
  28002. if (!this._vertexBuffers && this._delayInfo) {
  28003. for (kind in this._delayInfo) {
  28004. result.push(kind);
  28005. }
  28006. }
  28007. else {
  28008. for (kind in this._vertexBuffers) {
  28009. result.push(kind);
  28010. }
  28011. }
  28012. return result;
  28013. };
  28014. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28015. if (this._indexBuffer) {
  28016. this._engine._releaseBuffer(this._indexBuffer);
  28017. }
  28018. this._indices = indices;
  28019. if (this._meshes.length !== 0 && this._indices) {
  28020. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28021. }
  28022. if (totalVertices !== undefined) {
  28023. this._totalVertices = totalVertices;
  28024. }
  28025. var meshes = this._meshes;
  28026. var numOfMeshes = meshes.length;
  28027. for (var index = 0; index < numOfMeshes; index++) {
  28028. meshes[index]._createGlobalSubMesh();
  28029. }
  28030. this.notifyUpdate();
  28031. };
  28032. Geometry.prototype.getTotalIndices = function () {
  28033. if (!this.isReady()) {
  28034. return 0;
  28035. }
  28036. return this._indices.length;
  28037. };
  28038. Geometry.prototype.getIndices = function (copyWhenShared) {
  28039. if (!this.isReady()) {
  28040. return null;
  28041. }
  28042. var orig = this._indices;
  28043. if (!copyWhenShared || this._meshes.length === 1) {
  28044. return orig;
  28045. }
  28046. else {
  28047. var len = orig.length;
  28048. var copy = [];
  28049. for (var i = 0; i < len; i++) {
  28050. copy.push(orig[i]);
  28051. }
  28052. return copy;
  28053. }
  28054. };
  28055. Geometry.prototype.getIndexBuffer = function () {
  28056. if (!this.isReady()) {
  28057. return null;
  28058. }
  28059. return this._indexBuffer;
  28060. };
  28061. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28062. var meshes = this._meshes;
  28063. var index = meshes.indexOf(mesh);
  28064. if (index === -1) {
  28065. return;
  28066. }
  28067. for (var kind in this._vertexBuffers) {
  28068. this._vertexBuffers[kind].dispose();
  28069. }
  28070. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28071. this._indexBuffer = null;
  28072. }
  28073. meshes.splice(index, 1);
  28074. mesh._geometry = null;
  28075. if (meshes.length === 0 && shouldDispose) {
  28076. this.dispose();
  28077. }
  28078. };
  28079. Geometry.prototype.applyToMesh = function (mesh) {
  28080. if (mesh._geometry === this) {
  28081. return;
  28082. }
  28083. var previousGeometry = mesh._geometry;
  28084. if (previousGeometry) {
  28085. previousGeometry.releaseForMesh(mesh);
  28086. }
  28087. var meshes = this._meshes;
  28088. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28089. mesh._geometry = this;
  28090. this._scene.pushGeometry(this);
  28091. meshes.push(mesh);
  28092. if (this.isReady()) {
  28093. this._applyToMesh(mesh);
  28094. }
  28095. else {
  28096. mesh._boundingInfo = this._boundingInfo;
  28097. }
  28098. };
  28099. Geometry.prototype._applyToMesh = function (mesh) {
  28100. var numOfMeshes = this._meshes.length;
  28101. // vertexBuffers
  28102. for (var kind in this._vertexBuffers) {
  28103. if (numOfMeshes === 1) {
  28104. this._vertexBuffers[kind].create();
  28105. }
  28106. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28107. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28108. mesh._resetPointsArrayCache();
  28109. if (!this._extend) {
  28110. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28111. }
  28112. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28113. mesh._createGlobalSubMesh();
  28114. //bounding info was just created again, world matrix should be applied again.
  28115. mesh._updateBoundingInfo();
  28116. }
  28117. }
  28118. // indexBuffer
  28119. if (numOfMeshes === 1 && this._indices) {
  28120. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28121. }
  28122. if (this._indexBuffer) {
  28123. this._indexBuffer.references = numOfMeshes;
  28124. }
  28125. };
  28126. Geometry.prototype.notifyUpdate = function (kind) {
  28127. if (this.onGeometryUpdated) {
  28128. this.onGeometryUpdated(this, kind);
  28129. }
  28130. };
  28131. Geometry.prototype.load = function (scene, onLoaded) {
  28132. var _this = this;
  28133. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28134. return;
  28135. }
  28136. if (this.isReady()) {
  28137. if (onLoaded) {
  28138. onLoaded();
  28139. }
  28140. return;
  28141. }
  28142. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28143. scene._addPendingData(this);
  28144. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28145. _this._delayLoadingFunction(JSON.parse(data), _this);
  28146. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28147. _this._delayInfo = [];
  28148. scene._removePendingData(_this);
  28149. var meshes = _this._meshes;
  28150. var numOfMeshes = meshes.length;
  28151. for (var index = 0; index < numOfMeshes; index++) {
  28152. _this._applyToMesh(meshes[index]);
  28153. }
  28154. if (onLoaded) {
  28155. onLoaded();
  28156. }
  28157. }, function () { }, scene.database);
  28158. };
  28159. Geometry.prototype.isDisposed = function () {
  28160. return this._isDisposed;
  28161. };
  28162. Geometry.prototype.dispose = function () {
  28163. var meshes = this._meshes;
  28164. var numOfMeshes = meshes.length;
  28165. var index;
  28166. for (index = 0; index < numOfMeshes; index++) {
  28167. this.releaseForMesh(meshes[index]);
  28168. }
  28169. this._meshes = [];
  28170. for (var kind in this._vertexBuffers) {
  28171. this._vertexBuffers[kind].dispose();
  28172. }
  28173. this._vertexBuffers = [];
  28174. this._totalVertices = 0;
  28175. if (this._indexBuffer) {
  28176. this._engine._releaseBuffer(this._indexBuffer);
  28177. }
  28178. this._indexBuffer = null;
  28179. this._indices = [];
  28180. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28181. this.delayLoadingFile = null;
  28182. this._delayLoadingFunction = null;
  28183. this._delayInfo = [];
  28184. this._boundingInfo = null;
  28185. this._scene.removeGeometry(this);
  28186. this._isDisposed = true;
  28187. };
  28188. Geometry.prototype.copy = function (id) {
  28189. var vertexData = new BABYLON.VertexData();
  28190. vertexData.indices = [];
  28191. var indices = this.getIndices();
  28192. for (var index = 0; index < indices.length; index++) {
  28193. vertexData.indices.push(indices[index]);
  28194. }
  28195. var updatable = false;
  28196. var stopChecking = false;
  28197. var kind;
  28198. for (kind in this._vertexBuffers) {
  28199. // using slice() to make a copy of the array and not just reference it
  28200. var data = this.getVerticesData(kind);
  28201. if (data instanceof Float32Array) {
  28202. vertexData.set(new Float32Array(data), kind);
  28203. }
  28204. else {
  28205. vertexData.set(data.slice(0), kind);
  28206. }
  28207. if (!stopChecking) {
  28208. updatable = this.getVertexBuffer(kind).isUpdatable();
  28209. stopChecking = !updatable;
  28210. }
  28211. }
  28212. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28213. geometry.delayLoadState = this.delayLoadState;
  28214. geometry.delayLoadingFile = this.delayLoadingFile;
  28215. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28216. for (kind in this._delayInfo) {
  28217. geometry._delayInfo = geometry._delayInfo || [];
  28218. geometry._delayInfo.push(kind);
  28219. }
  28220. // Bounding info
  28221. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28222. return geometry;
  28223. };
  28224. Geometry.prototype.serialize = function () {
  28225. var serializationObject = {};
  28226. serializationObject.id = this.id;
  28227. if (BABYLON.Tags.HasTags(this)) {
  28228. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28229. }
  28230. return serializationObject;
  28231. };
  28232. Geometry.prototype.serializeVerticeData = function () {
  28233. var serializationObject = this.serialize();
  28234. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28235. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28236. }
  28237. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28238. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28239. }
  28240. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28241. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28242. }
  28243. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28244. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  28245. }
  28246. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28247. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  28248. }
  28249. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28250. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  28251. }
  28252. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28253. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  28254. }
  28255. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28256. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  28257. }
  28258. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28259. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28260. }
  28261. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28262. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28263. serializationObject.matricesIndices._isExpanded = true;
  28264. }
  28265. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28266. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28267. }
  28268. serializationObject.indices = this.getIndices();
  28269. return serializationObject;
  28270. };
  28271. // Statics
  28272. Geometry.ExtractFromMesh = function (mesh, id) {
  28273. var geometry = mesh._geometry;
  28274. if (!geometry) {
  28275. return null;
  28276. }
  28277. return geometry.copy(id);
  28278. };
  28279. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28280. // be aware Math.random() could cause collisions
  28281. Geometry.RandomId = function () {
  28282. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28283. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28284. return v.toString(16);
  28285. });
  28286. };
  28287. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28288. var scene = mesh.getScene();
  28289. // Geometry
  28290. var geometryId = parsedGeometry.geometryId;
  28291. if (geometryId) {
  28292. var geometry = scene.getGeometryByID(geometryId);
  28293. if (geometry) {
  28294. geometry.applyToMesh(mesh);
  28295. }
  28296. }
  28297. else if (parsedGeometry instanceof ArrayBuffer) {
  28298. var binaryInfo = mesh._binaryInfo;
  28299. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28300. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28301. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28302. }
  28303. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28304. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28305. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28306. }
  28307. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28308. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28309. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28310. }
  28311. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28312. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28313. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28314. }
  28315. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28316. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28317. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28318. }
  28319. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28320. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28321. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28322. }
  28323. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28324. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28325. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28326. }
  28327. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28328. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28329. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28330. }
  28331. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28332. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28333. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28334. }
  28335. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28336. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28337. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28338. }
  28339. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28340. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28341. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28342. }
  28343. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28344. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28345. mesh.setIndices(indicesData);
  28346. }
  28347. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28348. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28349. mesh.subMeshes = [];
  28350. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28351. var materialIndex = subMeshesData[(i * 5) + 0];
  28352. var verticesStart = subMeshesData[(i * 5) + 1];
  28353. var verticesCount = subMeshesData[(i * 5) + 2];
  28354. var indexStart = subMeshesData[(i * 5) + 3];
  28355. var indexCount = subMeshesData[(i * 5) + 4];
  28356. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28357. }
  28358. }
  28359. }
  28360. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28361. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  28362. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  28363. if (parsedGeometry.uvs) {
  28364. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  28365. }
  28366. if (parsedGeometry.uvs2) {
  28367. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  28368. }
  28369. if (parsedGeometry.uvs3) {
  28370. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  28371. }
  28372. if (parsedGeometry.uvs4) {
  28373. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  28374. }
  28375. if (parsedGeometry.uvs5) {
  28376. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  28377. }
  28378. if (parsedGeometry.uvs6) {
  28379. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  28380. }
  28381. if (parsedGeometry.colors) {
  28382. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  28383. }
  28384. if (parsedGeometry.matricesIndices) {
  28385. if (!parsedGeometry.matricesIndices._isExpanded) {
  28386. var floatIndices = [];
  28387. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28388. var matricesIndex = parsedGeometry.matricesIndices[i];
  28389. floatIndices.push(matricesIndex & 0x000000FF);
  28390. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28391. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28392. floatIndices.push(matricesIndex >> 24);
  28393. }
  28394. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  28395. }
  28396. else {
  28397. delete parsedGeometry.matricesIndices._isExpanded;
  28398. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  28399. }
  28400. }
  28401. if (parsedGeometry.matricesIndicesExtra) {
  28402. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28403. var floatIndices = [];
  28404. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28405. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28406. floatIndices.push(matricesIndex & 0x000000FF);
  28407. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28408. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28409. floatIndices.push(matricesIndex >> 24);
  28410. }
  28411. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  28412. }
  28413. else {
  28414. delete parsedGeometry.matricesIndices._isExpanded;
  28415. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  28416. }
  28417. }
  28418. if (parsedGeometry.matricesWeights) {
  28419. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  28420. }
  28421. if (parsedGeometry.matricesWeightsExtra) {
  28422. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  28423. }
  28424. mesh.setIndices(parsedGeometry.indices);
  28425. }
  28426. // SubMeshes
  28427. if (parsedGeometry.subMeshes) {
  28428. mesh.subMeshes = [];
  28429. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28430. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28431. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28432. }
  28433. }
  28434. // Flat shading
  28435. if (mesh._shouldGenerateFlatShading) {
  28436. mesh.convertToFlatShadedMesh();
  28437. delete mesh._shouldGenerateFlatShading;
  28438. }
  28439. // Update
  28440. mesh.computeWorldMatrix(true);
  28441. // Octree
  28442. if (scene['_selectionOctree']) {
  28443. scene['_selectionOctree'].addMesh(mesh);
  28444. }
  28445. };
  28446. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28447. if (scene.getGeometryByID(parsedVertexData.id)) {
  28448. return null; // null since geometry could be something else than a box...
  28449. }
  28450. var geometry = new Geometry(parsedVertexData.id, scene);
  28451. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28452. if (parsedVertexData.delayLoadingFile) {
  28453. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28454. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28455. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28456. geometry._delayInfo = [];
  28457. if (parsedVertexData.hasUVs) {
  28458. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28459. }
  28460. if (parsedVertexData.hasUVs2) {
  28461. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28462. }
  28463. if (parsedVertexData.hasUVs3) {
  28464. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28465. }
  28466. if (parsedVertexData.hasUVs4) {
  28467. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28468. }
  28469. if (parsedVertexData.hasUVs5) {
  28470. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28471. }
  28472. if (parsedVertexData.hasUVs6) {
  28473. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28474. }
  28475. if (parsedVertexData.hasColors) {
  28476. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28477. }
  28478. if (parsedVertexData.hasMatricesIndices) {
  28479. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28480. }
  28481. if (parsedVertexData.hasMatricesWeights) {
  28482. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28483. }
  28484. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28485. }
  28486. else {
  28487. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28488. }
  28489. scene.pushGeometry(geometry, true);
  28490. return geometry;
  28491. };
  28492. return Geometry;
  28493. })();
  28494. BABYLON.Geometry = Geometry;
  28495. /////// Primitives //////////////////////////////////////////////
  28496. var Geometry;
  28497. (function (Geometry) {
  28498. var Primitives;
  28499. (function (Primitives) {
  28500. /// Abstract class
  28501. var _Primitive = (function (_super) {
  28502. __extends(_Primitive, _super);
  28503. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28504. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  28505. this._canBeRegenerated = _canBeRegenerated;
  28506. this._beingRegenerated = true;
  28507. this.regenerate();
  28508. this._beingRegenerated = false;
  28509. }
  28510. _Primitive.prototype.canBeRegenerated = function () {
  28511. return this._canBeRegenerated;
  28512. };
  28513. _Primitive.prototype.regenerate = function () {
  28514. if (!this._canBeRegenerated) {
  28515. return;
  28516. }
  28517. this._beingRegenerated = true;
  28518. this.setAllVerticesData(this._regenerateVertexData(), false);
  28519. this._beingRegenerated = false;
  28520. };
  28521. _Primitive.prototype.asNewGeometry = function (id) {
  28522. return _super.prototype.copy.call(this, id);
  28523. };
  28524. // overrides
  28525. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28526. if (!this._beingRegenerated) {
  28527. return;
  28528. }
  28529. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28530. };
  28531. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28532. if (!this._beingRegenerated) {
  28533. return;
  28534. }
  28535. _super.prototype.setVerticesData.call(this, kind, data, false);
  28536. };
  28537. // to override
  28538. // protected
  28539. _Primitive.prototype._regenerateVertexData = function () {
  28540. throw new Error("Abstract method");
  28541. };
  28542. _Primitive.prototype.copy = function (id) {
  28543. throw new Error("Must be overriden in sub-classes.");
  28544. };
  28545. _Primitive.prototype.serialize = function () {
  28546. var serializationObject = _super.prototype.serialize.call(this);
  28547. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28548. return serializationObject;
  28549. };
  28550. return _Primitive;
  28551. })(Geometry);
  28552. Primitives._Primitive = _Primitive;
  28553. var Ribbon = (function (_super) {
  28554. __extends(Ribbon, _super);
  28555. // Members
  28556. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28557. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28558. _super.call(this, id, scene, canBeRegenerated, mesh);
  28559. this.pathArray = pathArray;
  28560. this.closeArray = closeArray;
  28561. this.closePath = closePath;
  28562. this.offset = offset;
  28563. this.side = side;
  28564. }
  28565. Ribbon.prototype._regenerateVertexData = function () {
  28566. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28567. };
  28568. Ribbon.prototype.copy = function (id) {
  28569. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28570. };
  28571. return Ribbon;
  28572. })(_Primitive);
  28573. Primitives.Ribbon = Ribbon;
  28574. var Box = (function (_super) {
  28575. __extends(Box, _super);
  28576. // Members
  28577. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28578. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28579. _super.call(this, id, scene, canBeRegenerated, mesh);
  28580. this.size = size;
  28581. this.side = side;
  28582. }
  28583. Box.prototype._regenerateVertexData = function () {
  28584. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28585. };
  28586. Box.prototype.copy = function (id) {
  28587. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28588. };
  28589. Box.prototype.serialize = function () {
  28590. var serializationObject = _super.prototype.serialize.call(this);
  28591. serializationObject.size = this.size;
  28592. return serializationObject;
  28593. };
  28594. Box.Parse = function (parsedBox, scene) {
  28595. if (scene.getGeometryByID(parsedBox.id)) {
  28596. return null; // null since geometry could be something else than a box...
  28597. }
  28598. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28599. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28600. scene.pushGeometry(box, true);
  28601. return box;
  28602. };
  28603. return Box;
  28604. })(_Primitive);
  28605. Primitives.Box = Box;
  28606. var Sphere = (function (_super) {
  28607. __extends(Sphere, _super);
  28608. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28609. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28610. _super.call(this, id, scene, canBeRegenerated, mesh);
  28611. this.segments = segments;
  28612. this.diameter = diameter;
  28613. this.side = side;
  28614. }
  28615. Sphere.prototype._regenerateVertexData = function () {
  28616. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28617. };
  28618. Sphere.prototype.copy = function (id) {
  28619. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28620. };
  28621. Sphere.prototype.serialize = function () {
  28622. var serializationObject = _super.prototype.serialize.call(this);
  28623. serializationObject.segments = this.segments;
  28624. serializationObject.diameter = this.diameter;
  28625. return serializationObject;
  28626. };
  28627. Sphere.Parse = function (parsedSphere, scene) {
  28628. if (scene.getGeometryByID(parsedSphere.id)) {
  28629. return null; // null since geometry could be something else than a sphere...
  28630. }
  28631. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28632. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28633. scene.pushGeometry(sphere, true);
  28634. return sphere;
  28635. };
  28636. return Sphere;
  28637. })(_Primitive);
  28638. Primitives.Sphere = Sphere;
  28639. var Disc = (function (_super) {
  28640. __extends(Disc, _super);
  28641. // Members
  28642. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28643. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28644. _super.call(this, id, scene, canBeRegenerated, mesh);
  28645. this.radius = radius;
  28646. this.tessellation = tessellation;
  28647. this.side = side;
  28648. }
  28649. Disc.prototype._regenerateVertexData = function () {
  28650. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28651. };
  28652. Disc.prototype.copy = function (id) {
  28653. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28654. };
  28655. return Disc;
  28656. })(_Primitive);
  28657. Primitives.Disc = Disc;
  28658. var Cylinder = (function (_super) {
  28659. __extends(Cylinder, _super);
  28660. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28661. if (subdivisions === void 0) { subdivisions = 1; }
  28662. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28663. _super.call(this, id, scene, canBeRegenerated, mesh);
  28664. this.height = height;
  28665. this.diameterTop = diameterTop;
  28666. this.diameterBottom = diameterBottom;
  28667. this.tessellation = tessellation;
  28668. this.subdivisions = subdivisions;
  28669. this.side = side;
  28670. }
  28671. Cylinder.prototype._regenerateVertexData = function () {
  28672. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28673. };
  28674. Cylinder.prototype.copy = function (id) {
  28675. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28676. };
  28677. Cylinder.prototype.serialize = function () {
  28678. var serializationObject = _super.prototype.serialize.call(this);
  28679. serializationObject.height = this.height;
  28680. serializationObject.diameterTop = this.diameterTop;
  28681. serializationObject.diameterBottom = this.diameterBottom;
  28682. serializationObject.tessellation = this.tessellation;
  28683. return serializationObject;
  28684. };
  28685. Cylinder.Parse = function (parsedCylinder, scene) {
  28686. if (scene.getGeometryByID(parsedCylinder.id)) {
  28687. return null; // null since geometry could be something else than a cylinder...
  28688. }
  28689. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28690. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28691. scene.pushGeometry(cylinder, true);
  28692. return cylinder;
  28693. };
  28694. return Cylinder;
  28695. })(_Primitive);
  28696. Primitives.Cylinder = Cylinder;
  28697. var Torus = (function (_super) {
  28698. __extends(Torus, _super);
  28699. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28700. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28701. _super.call(this, id, scene, canBeRegenerated, mesh);
  28702. this.diameter = diameter;
  28703. this.thickness = thickness;
  28704. this.tessellation = tessellation;
  28705. this.side = side;
  28706. }
  28707. Torus.prototype._regenerateVertexData = function () {
  28708. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28709. };
  28710. Torus.prototype.copy = function (id) {
  28711. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28712. };
  28713. Torus.prototype.serialize = function () {
  28714. var serializationObject = _super.prototype.serialize.call(this);
  28715. serializationObject.diameter = this.diameter;
  28716. serializationObject.thickness = this.thickness;
  28717. serializationObject.tessellation = this.tessellation;
  28718. return serializationObject;
  28719. };
  28720. Torus.Parse = function (parsedTorus, scene) {
  28721. if (scene.getGeometryByID(parsedTorus.id)) {
  28722. return null; // null since geometry could be something else than a torus...
  28723. }
  28724. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28725. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28726. scene.pushGeometry(torus, true);
  28727. return torus;
  28728. };
  28729. return Torus;
  28730. })(_Primitive);
  28731. Primitives.Torus = Torus;
  28732. var Ground = (function (_super) {
  28733. __extends(Ground, _super);
  28734. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28735. _super.call(this, id, scene, canBeRegenerated, mesh);
  28736. this.width = width;
  28737. this.height = height;
  28738. this.subdivisions = subdivisions;
  28739. }
  28740. Ground.prototype._regenerateVertexData = function () {
  28741. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28742. };
  28743. Ground.prototype.copy = function (id) {
  28744. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28745. };
  28746. Ground.prototype.serialize = function () {
  28747. var serializationObject = _super.prototype.serialize.call(this);
  28748. serializationObject.width = this.width;
  28749. serializationObject.height = this.height;
  28750. serializationObject.subdivisions = this.subdivisions;
  28751. return serializationObject;
  28752. };
  28753. Ground.Parse = function (parsedGround, scene) {
  28754. if (scene.getGeometryByID(parsedGround.id)) {
  28755. return null; // null since geometry could be something else than a ground...
  28756. }
  28757. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28758. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28759. scene.pushGeometry(ground, true);
  28760. return ground;
  28761. };
  28762. return Ground;
  28763. })(_Primitive);
  28764. Primitives.Ground = Ground;
  28765. var TiledGround = (function (_super) {
  28766. __extends(TiledGround, _super);
  28767. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28768. _super.call(this, id, scene, canBeRegenerated, mesh);
  28769. this.xmin = xmin;
  28770. this.zmin = zmin;
  28771. this.xmax = xmax;
  28772. this.zmax = zmax;
  28773. this.subdivisions = subdivisions;
  28774. this.precision = precision;
  28775. }
  28776. TiledGround.prototype._regenerateVertexData = function () {
  28777. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28778. };
  28779. TiledGround.prototype.copy = function (id) {
  28780. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28781. };
  28782. return TiledGround;
  28783. })(_Primitive);
  28784. Primitives.TiledGround = TiledGround;
  28785. var Plane = (function (_super) {
  28786. __extends(Plane, _super);
  28787. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28788. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28789. _super.call(this, id, scene, canBeRegenerated, mesh);
  28790. this.size = size;
  28791. this.side = side;
  28792. }
  28793. Plane.prototype._regenerateVertexData = function () {
  28794. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28795. };
  28796. Plane.prototype.copy = function (id) {
  28797. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28798. };
  28799. Plane.prototype.serialize = function () {
  28800. var serializationObject = _super.prototype.serialize.call(this);
  28801. serializationObject.size = this.size;
  28802. return serializationObject;
  28803. };
  28804. Plane.Parse = function (parsedPlane, scene) {
  28805. if (scene.getGeometryByID(parsedPlane.id)) {
  28806. return null; // null since geometry could be something else than a ground...
  28807. }
  28808. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28809. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28810. scene.pushGeometry(plane, true);
  28811. return plane;
  28812. };
  28813. return Plane;
  28814. })(_Primitive);
  28815. Primitives.Plane = Plane;
  28816. var TorusKnot = (function (_super) {
  28817. __extends(TorusKnot, _super);
  28818. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28819. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28820. _super.call(this, id, scene, canBeRegenerated, mesh);
  28821. this.radius = radius;
  28822. this.tube = tube;
  28823. this.radialSegments = radialSegments;
  28824. this.tubularSegments = tubularSegments;
  28825. this.p = p;
  28826. this.q = q;
  28827. this.side = side;
  28828. }
  28829. TorusKnot.prototype._regenerateVertexData = function () {
  28830. 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 });
  28831. };
  28832. TorusKnot.prototype.copy = function (id) {
  28833. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28834. };
  28835. TorusKnot.prototype.serialize = function () {
  28836. var serializationObject = _super.prototype.serialize.call(this);
  28837. serializationObject.radius = this.radius;
  28838. serializationObject.tube = this.tube;
  28839. serializationObject.radialSegments = this.radialSegments;
  28840. serializationObject.tubularSegments = this.tubularSegments;
  28841. serializationObject.p = this.p;
  28842. serializationObject.q = this.q;
  28843. return serializationObject;
  28844. };
  28845. ;
  28846. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28847. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28848. return null; // null since geometry could be something else than a ground...
  28849. }
  28850. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28851. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28852. scene.pushGeometry(torusKnot, true);
  28853. return torusKnot;
  28854. };
  28855. return TorusKnot;
  28856. })(_Primitive);
  28857. Primitives.TorusKnot = TorusKnot;
  28858. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28859. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28860. })(BABYLON || (BABYLON = {}));
  28861. var BABYLON;
  28862. (function (BABYLON) {
  28863. var GroundMesh = (function (_super) {
  28864. __extends(GroundMesh, _super);
  28865. function GroundMesh(name, scene) {
  28866. _super.call(this, name, scene);
  28867. this.generateOctree = false;
  28868. this._worldInverse = new BABYLON.Matrix();
  28869. }
  28870. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28871. get: function () {
  28872. return this._subdivisions;
  28873. },
  28874. enumerable: true,
  28875. configurable: true
  28876. });
  28877. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28878. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28879. this._subdivisions = chunksCount;
  28880. this.subdivide(this._subdivisions);
  28881. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28882. };
  28883. /**
  28884. * Returns a height (y) value in the Worl system :
  28885. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28886. * Returns the ground y position if (x, z) are outside the ground surface.
  28887. * Not pertinent if the ground is rotated.
  28888. */
  28889. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28890. // express x and y in the ground local system
  28891. x -= this.position.x;
  28892. z -= this.position.z;
  28893. x /= this.scaling.x;
  28894. z /= this.scaling.z;
  28895. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28896. return this.position.y;
  28897. }
  28898. if (!this._heightQuads || this._heightQuads.length == 0) {
  28899. this._initHeightQuads();
  28900. this._computeHeightQuads();
  28901. }
  28902. var facet = this._getFacetAt(x, z);
  28903. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  28904. // return y in the World system
  28905. return y * this.scaling.y + this.position.y;
  28906. };
  28907. /**
  28908. * Returns a normalized vector (Vector3) orthogonal to the ground
  28909. * at the ground coordinates (x, z) expressed in the World system.
  28910. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  28911. * Not pertinent if the ground is rotated.
  28912. */
  28913. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  28914. var normal = new BABYLON.Vector3(0, 1, 0);
  28915. this.getNormalAtCoordinatesToRef(x, z, normal);
  28916. return normal;
  28917. };
  28918. /**
  28919. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  28920. * at the ground coordinates (x, z) expressed in the World system.
  28921. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  28922. * Not pertinent if the ground is rotated.
  28923. */
  28924. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  28925. // express x and y in the ground local system
  28926. x -= this.position.x;
  28927. z -= this.position.z;
  28928. x /= this.scaling.x;
  28929. z /= this.scaling.z;
  28930. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28931. return;
  28932. }
  28933. if (!this._heightQuads || this._heightQuads.length == 0) {
  28934. this._initHeightQuads();
  28935. this._computeHeightQuads();
  28936. }
  28937. var facet = this._getFacetAt(x, z);
  28938. ref.x = facet.x;
  28939. ref.y = facet.y;
  28940. ref.z = facet.z;
  28941. };
  28942. /**
  28943. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  28944. * if the ground has been updated.
  28945. * This can be used in the render loop
  28946. */
  28947. GroundMesh.prototype.updateCoordinateHeights = function () {
  28948. if (!this._heightQuads || this._heightQuads.length == 0) {
  28949. this._initHeightQuads();
  28950. }
  28951. this._computeHeightQuads();
  28952. };
  28953. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  28954. GroundMesh.prototype._getFacetAt = function (x, z) {
  28955. // retrieve col and row from x, z coordinates in the ground local system
  28956. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  28957. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  28958. var quad = this._heightQuads[row * this._subdivisions + col];
  28959. var facet;
  28960. if (z < quad.slope.x * x + quad.slope.y) {
  28961. facet = quad.facet1;
  28962. }
  28963. else {
  28964. facet = quad.facet2;
  28965. }
  28966. return facet;
  28967. };
  28968. // Creates and populates the heightMap array with "facet" elements :
  28969. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  28970. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28971. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28972. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28973. GroundMesh.prototype._initHeightQuads = function () {
  28974. this._heightQuads = new Array();
  28975. for (var row = 0; row < this._subdivisions; row++) {
  28976. for (var col = 0; col < this._subdivisions; col++) {
  28977. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  28978. this._heightQuads[row * this._subdivisions + col] = quad;
  28979. }
  28980. }
  28981. };
  28982. // Compute each quad element values and update the the heightMap array :
  28983. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28984. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28985. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28986. GroundMesh.prototype._computeHeightQuads = function () {
  28987. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28988. var v1 = BABYLON.Tmp.Vector3[0];
  28989. var v2 = BABYLON.Tmp.Vector3[1];
  28990. var v3 = BABYLON.Tmp.Vector3[2];
  28991. var v4 = BABYLON.Tmp.Vector3[3];
  28992. var v1v2 = BABYLON.Tmp.Vector3[4];
  28993. var v1v3 = BABYLON.Tmp.Vector3[5];
  28994. var v1v4 = BABYLON.Tmp.Vector3[6];
  28995. var norm1 = BABYLON.Tmp.Vector3[7];
  28996. var norm2 = BABYLON.Tmp.Vector3[8];
  28997. var i = 0;
  28998. var j = 0;
  28999. var k = 0;
  29000. var cd = 0; // 2D slope coefficient : z = cd * x + h
  29001. var h = 0;
  29002. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  29003. var d2 = 0;
  29004. for (var row = 0; row < this._subdivisions; row++) {
  29005. for (var col = 0; col < this._subdivisions; col++) {
  29006. i = col * 3;
  29007. j = row * (this._subdivisions + 1) * 3;
  29008. k = (row + 1) * (this._subdivisions + 1) * 3;
  29009. v1.x = positions[j + i];
  29010. v1.y = positions[j + i + 1];
  29011. v1.z = positions[j + i + 2];
  29012. v2.x = positions[j + i + 3];
  29013. v2.y = positions[j + i + 4];
  29014. v2.z = positions[j + i + 5];
  29015. v3.x = positions[k + i];
  29016. v3.y = positions[k + i + 1];
  29017. v3.z = positions[k + i + 2];
  29018. v4.x = positions[k + i + 3];
  29019. v4.y = positions[k + i + 4];
  29020. v4.z = positions[k + i + 5];
  29021. // 2D slope V1V4
  29022. cd = (v4.z - v1.z) / (v4.x - v1.x);
  29023. h = v1.z - cd * v1.x; // v1 belongs to the slope
  29024. // facet equations :
  29025. // we compute each facet normal vector
  29026. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  29027. // we compute the value d by applying the equation to v1 which belongs to the plane
  29028. // then we store the facet equation in a Vector4
  29029. v2.subtractToRef(v1, v1v2);
  29030. v3.subtractToRef(v1, v1v3);
  29031. v4.subtractToRef(v1, v1v4);
  29032. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  29033. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  29034. norm1.normalize();
  29035. norm2.normalize();
  29036. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  29037. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  29038. var quad = this._heightQuads[row * this._subdivisions + col];
  29039. quad.slope.copyFromFloats(cd, h);
  29040. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  29041. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  29042. }
  29043. }
  29044. };
  29045. return GroundMesh;
  29046. })(BABYLON.Mesh);
  29047. BABYLON.GroundMesh = GroundMesh;
  29048. })(BABYLON || (BABYLON = {}));
  29049. var BABYLON;
  29050. (function (BABYLON) {
  29051. var LinesMesh = (function (_super) {
  29052. __extends(LinesMesh, _super);
  29053. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29054. if (parent === void 0) { parent = null; }
  29055. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29056. this.color = new BABYLON.Color3(1, 1, 1);
  29057. this.alpha = 1;
  29058. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29059. attributes: ["position"],
  29060. uniforms: ["worldViewProjection", "color"],
  29061. needAlphaBlending: true
  29062. });
  29063. }
  29064. Object.defineProperty(LinesMesh.prototype, "material", {
  29065. get: function () {
  29066. return this._colorShader;
  29067. },
  29068. enumerable: true,
  29069. configurable: true
  29070. });
  29071. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29072. get: function () {
  29073. return false;
  29074. },
  29075. enumerable: true,
  29076. configurable: true
  29077. });
  29078. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29079. get: function () {
  29080. return false;
  29081. },
  29082. enumerable: true,
  29083. configurable: true
  29084. });
  29085. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29086. var engine = this.getScene().getEngine();
  29087. var indexToBind = this._geometry.getIndexBuffer();
  29088. // VBOs
  29089. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29090. // Color
  29091. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29092. };
  29093. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29094. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29095. return;
  29096. }
  29097. var engine = this.getScene().getEngine();
  29098. // Draw order
  29099. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29100. };
  29101. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29102. return null;
  29103. };
  29104. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29105. this._colorShader.dispose();
  29106. _super.prototype.dispose.call(this, doNotRecurse);
  29107. };
  29108. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29109. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29110. };
  29111. return LinesMesh;
  29112. })(BABYLON.Mesh);
  29113. BABYLON.LinesMesh = LinesMesh;
  29114. })(BABYLON || (BABYLON = {}));
  29115. var BABYLON;
  29116. (function (BABYLON) {
  29117. var DebugLayer = (function () {
  29118. function DebugLayer(scene) {
  29119. var _this = this;
  29120. this._transformationMatrix = BABYLON.Matrix.Identity();
  29121. this._enabled = false;
  29122. this._labelsEnabled = false;
  29123. this._displayStatistics = true;
  29124. this._displayTree = false;
  29125. this._displayLogs = false;
  29126. this._identityMatrix = BABYLON.Matrix.Identity();
  29127. this.axisRatio = 0.02;
  29128. this.accentColor = "orange";
  29129. this._scene = scene;
  29130. this._syncPositions = function () {
  29131. var engine = _this._scene.getEngine();
  29132. var canvasRect = engine.getRenderingCanvasClientRect();
  29133. if (_this._showUI) {
  29134. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29135. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29136. _this._statsDiv.style.width = "400px";
  29137. _this._statsDiv.style.height = "auto";
  29138. _this._statsSubsetDiv.style.maxHeight = "240px";
  29139. _this._optionsDiv.style.left = "0px";
  29140. _this._optionsDiv.style.top = "10px";
  29141. _this._optionsDiv.style.width = "200px";
  29142. _this._optionsDiv.style.height = "auto";
  29143. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29144. _this._logDiv.style.left = "0px";
  29145. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29146. _this._logDiv.style.width = "600px";
  29147. _this._logDiv.style.height = "160px";
  29148. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29149. _this._treeDiv.style.top = "10px";
  29150. _this._treeDiv.style.width = "300px";
  29151. _this._treeDiv.style.height = "auto";
  29152. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29153. }
  29154. _this._globalDiv.style.left = canvasRect.left + "px";
  29155. _this._globalDiv.style.top = canvasRect.top + "px";
  29156. _this._drawingCanvas.style.left = "0px";
  29157. _this._drawingCanvas.style.top = "0px";
  29158. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29159. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29160. var devicePixelRatio = window.devicePixelRatio || 1;
  29161. var context = _this._drawingContext;
  29162. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29163. context.mozBackingStorePixelRatio ||
  29164. context.msBackingStorePixelRatio ||
  29165. context.oBackingStorePixelRatio ||
  29166. context.backingStorePixelRatio || 1;
  29167. _this._ratio = devicePixelRatio / backingStoreRatio;
  29168. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29169. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29170. };
  29171. this._onCanvasClick = function (evt) {
  29172. _this._clickPosition = {
  29173. x: evt.clientX * _this._ratio,
  29174. y: evt.clientY * _this._ratio
  29175. };
  29176. };
  29177. this._syncUI = function () {
  29178. if (_this._showUI) {
  29179. if (_this._displayStatistics) {
  29180. _this._displayStats();
  29181. _this._statsDiv.style.display = "";
  29182. }
  29183. else {
  29184. _this._statsDiv.style.display = "none";
  29185. }
  29186. if (_this._displayLogs) {
  29187. _this._logDiv.style.display = "";
  29188. }
  29189. else {
  29190. _this._logDiv.style.display = "none";
  29191. }
  29192. if (_this._displayTree) {
  29193. _this._treeDiv.style.display = "";
  29194. if (_this._needToRefreshMeshesTree) {
  29195. _this._needToRefreshMeshesTree = false;
  29196. _this._refreshMeshesTreeContent();
  29197. }
  29198. }
  29199. else {
  29200. _this._treeDiv.style.display = "none";
  29201. }
  29202. }
  29203. };
  29204. this._syncData = function () {
  29205. if (_this._labelsEnabled || !_this._showUI) {
  29206. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29207. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29208. var engine = _this._scene.getEngine();
  29209. var viewport = _this._camera.viewport;
  29210. var globalViewport = viewport.toGlobal(engine);
  29211. // Meshes
  29212. var meshes = _this._camera.getActiveMeshes();
  29213. var index;
  29214. var projectedPosition;
  29215. for (index = 0; index < meshes.length; index++) {
  29216. var mesh = meshes.data[index];
  29217. var position = mesh.getBoundingInfo().boundingSphere.center;
  29218. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29219. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29220. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29221. }
  29222. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29223. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29224. }
  29225. }
  29226. // Cameras
  29227. var cameras = _this._scene.cameras;
  29228. for (index = 0; index < cameras.length; index++) {
  29229. var camera = cameras[index];
  29230. if (camera === _this._camera) {
  29231. continue;
  29232. }
  29233. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29234. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29235. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29236. _this._camera.detachControl(engine.getRenderingCanvas());
  29237. _this._camera = camera;
  29238. _this._camera.attachControl(engine.getRenderingCanvas());
  29239. }, function () { return "purple"; });
  29240. }
  29241. }
  29242. // Lights
  29243. var lights = _this._scene.lights;
  29244. for (index = 0; index < lights.length; index++) {
  29245. var light = lights[index];
  29246. if (light.position) {
  29247. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29248. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29249. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29250. light.setEnabled(!light.isEnabled());
  29251. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29252. }
  29253. }
  29254. }
  29255. }
  29256. _this._clickPosition = undefined;
  29257. };
  29258. }
  29259. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29260. while (this._treeSubsetDiv.hasChildNodes()) {
  29261. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29262. }
  29263. // Add meshes
  29264. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29265. sortedArray.sort(function (a, b) {
  29266. if (a.name === b.name) {
  29267. return 0;
  29268. }
  29269. return (a.name > b.name) ? 1 : -1;
  29270. });
  29271. for (var index = 0; index < sortedArray.length; index++) {
  29272. var mesh = sortedArray[index];
  29273. if (!mesh.isEnabled()) {
  29274. continue;
  29275. }
  29276. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29277. m.isVisible = element.checked;
  29278. }, mesh);
  29279. }
  29280. };
  29281. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29282. this._drawingContext.beginPath();
  29283. this._drawingContext.moveTo(zero.x, zero.y);
  29284. this._drawingContext.lineTo(unit.x, unit.y);
  29285. this._drawingContext.strokeStyle = color;
  29286. this._drawingContext.lineWidth = 4;
  29287. this._drawingContext.stroke();
  29288. this._drawingContext.font = "normal 14px Segoe UI";
  29289. this._drawingContext.fillStyle = color;
  29290. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29291. };
  29292. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29293. var position = mesh.getBoundingInfo().boundingSphere.center;
  29294. var worldMatrix = mesh.getWorldMatrix();
  29295. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29296. var unit = (unprojectedVector.subtract(position)).length();
  29297. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29298. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29299. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29300. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29301. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29302. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29303. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29304. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29305. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29306. };
  29307. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29308. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29309. this._drawingContext.font = "normal 12px Segoe UI";
  29310. var textMetrics = this._drawingContext.measureText(text);
  29311. var centerX = projectedPosition.x - textMetrics.width / 2;
  29312. var centerY = projectedPosition.y;
  29313. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29314. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29315. onClick();
  29316. }
  29317. this._drawingContext.beginPath();
  29318. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29319. this._drawingContext.fillStyle = getFillStyle();
  29320. this._drawingContext.globalAlpha = 0.5;
  29321. this._drawingContext.fill();
  29322. this._drawingContext.globalAlpha = 1.0;
  29323. this._drawingContext.strokeStyle = '#FFFFFF';
  29324. this._drawingContext.lineWidth = 1;
  29325. this._drawingContext.stroke();
  29326. this._drawingContext.fillStyle = "#FFFFFF";
  29327. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29328. this._drawingContext.beginPath();
  29329. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29330. this._drawingContext.fill();
  29331. }
  29332. };
  29333. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29334. if (!this._clickPosition) {
  29335. return false;
  29336. }
  29337. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29338. return false;
  29339. }
  29340. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29341. return false;
  29342. }
  29343. return true;
  29344. };
  29345. DebugLayer.prototype.isVisible = function () {
  29346. return this._enabled;
  29347. };
  29348. DebugLayer.prototype.hide = function () {
  29349. if (!this._enabled) {
  29350. return;
  29351. }
  29352. this._enabled = false;
  29353. var engine = this._scene.getEngine();
  29354. this._scene.unregisterBeforeRender(this._syncData);
  29355. this._scene.unregisterAfterRender(this._syncUI);
  29356. this._rootElement.removeChild(this._globalDiv);
  29357. this._scene.forceShowBoundingBoxes = false;
  29358. this._scene.forceWireframe = false;
  29359. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29360. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29361. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29362. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29363. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29364. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29365. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29366. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  29367. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  29368. this._scene.shadowsEnabled = true;
  29369. this._scene.particlesEnabled = true;
  29370. this._scene.postProcessesEnabled = true;
  29371. this._scene.collisionsEnabled = true;
  29372. this._scene.lightsEnabled = true;
  29373. this._scene.texturesEnabled = true;
  29374. this._scene.lensFlaresEnabled = true;
  29375. this._scene.proceduralTexturesEnabled = true;
  29376. this._scene.renderTargetsEnabled = true;
  29377. this._scene.probesEnabled = true;
  29378. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29379. };
  29380. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  29381. if (showUI === void 0) { showUI = true; }
  29382. if (camera === void 0) { camera = null; }
  29383. if (rootElement === void 0) { rootElement = null; }
  29384. if (this._enabled) {
  29385. return;
  29386. }
  29387. this._enabled = true;
  29388. if (camera) {
  29389. this._camera = camera;
  29390. }
  29391. else {
  29392. this._camera = this._scene.activeCamera;
  29393. }
  29394. this._showUI = showUI;
  29395. var engine = this._scene.getEngine();
  29396. this._globalDiv = document.createElement("div");
  29397. this._rootElement = rootElement || document.body;
  29398. this._rootElement.appendChild(this._globalDiv);
  29399. this._generateDOMelements();
  29400. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29401. this._syncPositions();
  29402. this._scene.registerBeforeRender(this._syncData);
  29403. this._scene.registerAfterRender(this._syncUI);
  29404. };
  29405. DebugLayer.prototype._clearLabels = function () {
  29406. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29407. for (var index = 0; index < this._scene.meshes.length; index++) {
  29408. var mesh = this._scene.meshes[index];
  29409. mesh.renderOverlay = false;
  29410. }
  29411. };
  29412. DebugLayer.prototype._generateheader = function (root, text) {
  29413. var header = document.createElement("div");
  29414. header.innerHTML = text + "&nbsp;";
  29415. header.style.textAlign = "right";
  29416. header.style.width = "100%";
  29417. header.style.color = "white";
  29418. header.style.backgroundColor = "Black";
  29419. header.style.padding = "5px 5px 4px 0px";
  29420. header.style.marginLeft = "-5px";
  29421. header.style.fontWeight = "bold";
  29422. root.appendChild(header);
  29423. };
  29424. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29425. var label = document.createElement("label");
  29426. label.innerHTML = title;
  29427. label.style.color = color;
  29428. root.appendChild(label);
  29429. root.appendChild(document.createElement("br"));
  29430. };
  29431. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29432. if (tag === void 0) { tag = null; }
  29433. var label = document.createElement("label");
  29434. var boundingBoxesCheckbox = document.createElement("input");
  29435. boundingBoxesCheckbox.type = "checkbox";
  29436. boundingBoxesCheckbox.checked = initialState;
  29437. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29438. task(evt.target, tag);
  29439. });
  29440. label.appendChild(boundingBoxesCheckbox);
  29441. var container = document.createElement("span");
  29442. var leftPart = document.createElement("span");
  29443. var rightPart = document.createElement("span");
  29444. rightPart.style.cssFloat = "right";
  29445. leftPart.innerHTML = leftTitle;
  29446. rightPart.innerHTML = rightTitle;
  29447. rightPart.style.fontSize = "12px";
  29448. rightPart.style.maxWidth = "200px";
  29449. container.appendChild(leftPart);
  29450. container.appendChild(rightPart);
  29451. label.appendChild(container);
  29452. root.appendChild(label);
  29453. root.appendChild(document.createElement("br"));
  29454. };
  29455. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29456. if (tag === void 0) { tag = null; }
  29457. var label = document.createElement("label");
  29458. var checkBox = document.createElement("input");
  29459. checkBox.type = "checkbox";
  29460. checkBox.checked = initialState;
  29461. checkBox.addEventListener("change", function (evt) {
  29462. task(evt.target, tag);
  29463. });
  29464. label.appendChild(checkBox);
  29465. label.appendChild(document.createTextNode(title));
  29466. root.appendChild(label);
  29467. root.appendChild(document.createElement("br"));
  29468. };
  29469. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29470. if (tag === void 0) { tag = null; }
  29471. var button = document.createElement("button");
  29472. button.innerHTML = title;
  29473. button.style.height = "24px";
  29474. button.style.width = "150px";
  29475. button.style.marginBottom = "5px";
  29476. button.style.color = "#444444";
  29477. button.style.border = "1px solid white";
  29478. button.className = "debugLayerButton";
  29479. button.addEventListener("click", function (evt) {
  29480. task(evt.target, tag);
  29481. });
  29482. root.appendChild(button);
  29483. root.appendChild(document.createElement("br"));
  29484. };
  29485. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29486. if (tag === void 0) { tag = null; }
  29487. var label = document.createElement("label");
  29488. var boundingBoxesRadio = document.createElement("input");
  29489. boundingBoxesRadio.type = "radio";
  29490. boundingBoxesRadio.name = name;
  29491. boundingBoxesRadio.checked = initialState;
  29492. boundingBoxesRadio.addEventListener("change", function (evt) {
  29493. task(evt.target, tag);
  29494. });
  29495. label.appendChild(boundingBoxesRadio);
  29496. label.appendChild(document.createTextNode(title));
  29497. root.appendChild(label);
  29498. root.appendChild(document.createElement("br"));
  29499. };
  29500. DebugLayer.prototype._generateDOMelements = function () {
  29501. var _this = this;
  29502. this._globalDiv.id = "DebugLayer";
  29503. this._globalDiv.style.position = "absolute";
  29504. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29505. this._globalDiv.style.fontSize = "14px";
  29506. this._globalDiv.style.color = "white";
  29507. // Drawing canvas
  29508. this._drawingCanvas = document.createElement("canvas");
  29509. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29510. this._drawingCanvas.style.position = "absolute";
  29511. this._drawingCanvas.style.pointerEvents = "none";
  29512. this._drawingCanvas.style.backgroundColor = "transparent";
  29513. this._drawingContext = this._drawingCanvas.getContext("2d");
  29514. this._globalDiv.appendChild(this._drawingCanvas);
  29515. if (this._showUI) {
  29516. var background = "rgba(128, 128, 128, 0.4)";
  29517. var border = "rgb(180, 180, 180) solid 1px";
  29518. // Stats
  29519. this._statsDiv = document.createElement("div");
  29520. this._statsDiv.id = "DebugLayerStats";
  29521. this._statsDiv.style.border = border;
  29522. this._statsDiv.style.position = "absolute";
  29523. this._statsDiv.style.background = background;
  29524. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29525. this._generateheader(this._statsDiv, "STATISTICS");
  29526. this._statsSubsetDiv = document.createElement("div");
  29527. this._statsSubsetDiv.style.paddingTop = "5px";
  29528. this._statsSubsetDiv.style.paddingBottom = "5px";
  29529. this._statsSubsetDiv.style.overflowY = "auto";
  29530. this._statsDiv.appendChild(this._statsSubsetDiv);
  29531. // Tree
  29532. this._treeDiv = document.createElement("div");
  29533. this._treeDiv.id = "DebugLayerTree";
  29534. this._treeDiv.style.border = border;
  29535. this._treeDiv.style.position = "absolute";
  29536. this._treeDiv.style.background = background;
  29537. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29538. this._treeDiv.style.display = "none";
  29539. this._generateheader(this._treeDiv, "MESHES TREE");
  29540. this._treeSubsetDiv = document.createElement("div");
  29541. this._treeSubsetDiv.style.paddingTop = "5px";
  29542. this._treeSubsetDiv.style.paddingRight = "5px";
  29543. this._treeSubsetDiv.style.overflowY = "auto";
  29544. this._treeSubsetDiv.style.maxHeight = "300px";
  29545. this._treeDiv.appendChild(this._treeSubsetDiv);
  29546. this._needToRefreshMeshesTree = true;
  29547. // Logs
  29548. this._logDiv = document.createElement("div");
  29549. this._logDiv.style.border = border;
  29550. this._logDiv.id = "DebugLayerLogs";
  29551. this._logDiv.style.position = "absolute";
  29552. this._logDiv.style.background = background;
  29553. this._logDiv.style.padding = "0px 0px 0px 5px";
  29554. this._logDiv.style.display = "none";
  29555. this._generateheader(this._logDiv, "LOGS");
  29556. this._logSubsetDiv = document.createElement("div");
  29557. this._logSubsetDiv.style.height = "127px";
  29558. this._logSubsetDiv.style.paddingTop = "5px";
  29559. this._logSubsetDiv.style.overflowY = "auto";
  29560. this._logSubsetDiv.style.fontSize = "12px";
  29561. this._logSubsetDiv.style.fontFamily = "consolas";
  29562. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29563. this._logDiv.appendChild(this._logSubsetDiv);
  29564. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29565. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29566. };
  29567. // Options
  29568. this._optionsDiv = document.createElement("div");
  29569. this._optionsDiv.id = "DebugLayerOptions";
  29570. this._optionsDiv.style.border = border;
  29571. this._optionsDiv.style.position = "absolute";
  29572. this._optionsDiv.style.background = background;
  29573. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29574. this._optionsDiv.style.overflowY = "auto";
  29575. this._generateheader(this._optionsDiv, "OPTIONS");
  29576. this._optionsSubsetDiv = document.createElement("div");
  29577. this._optionsSubsetDiv.style.paddingTop = "5px";
  29578. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29579. this._optionsSubsetDiv.style.overflowY = "auto";
  29580. this._optionsSubsetDiv.style.maxHeight = "200px";
  29581. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29582. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29583. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29584. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29585. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29586. _this._displayTree = element.checked;
  29587. _this._needToRefreshMeshesTree = true;
  29588. });
  29589. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29590. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29591. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29592. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29593. _this._labelsEnabled = element.checked;
  29594. if (!_this._labelsEnabled) {
  29595. _this._clearLabels();
  29596. }
  29597. });
  29598. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29599. if (element.checked) {
  29600. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29601. }
  29602. else {
  29603. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29604. }
  29605. });
  29606. ;
  29607. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29608. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29609. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29610. if (element.checked) {
  29611. _this._scene.forceWireframe = false;
  29612. _this._scene.forcePointsCloud = false;
  29613. }
  29614. });
  29615. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29616. if (element.checked) {
  29617. _this._scene.forceWireframe = true;
  29618. _this._scene.forcePointsCloud = false;
  29619. }
  29620. });
  29621. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29622. if (element.checked) {
  29623. _this._scene.forceWireframe = false;
  29624. _this._scene.forcePointsCloud = true;
  29625. }
  29626. });
  29627. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29628. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29629. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29630. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29631. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29632. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29633. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29634. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29635. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29636. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  29637. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  29638. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29639. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29640. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29641. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29642. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29643. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29644. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29645. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29646. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29647. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29648. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  29649. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29650. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29651. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29652. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29653. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29654. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29655. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  29656. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29657. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29658. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29659. if (element.checked) {
  29660. _this._scene.headphone = true;
  29661. }
  29662. });
  29663. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29664. if (element.checked) {
  29665. _this._scene.headphone = false;
  29666. }
  29667. });
  29668. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29669. _this._scene.audioEnabled = !element.checked;
  29670. });
  29671. }
  29672. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29673. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29674. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29675. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  29676. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  29677. if (_this._camera) {
  29678. console.log(_this._camera);
  29679. }
  29680. else {
  29681. console.warn("No camera defined, or debug layer created before camera creation!");
  29682. }
  29683. });
  29684. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29685. this._globalDiv.appendChild(this._statsDiv);
  29686. this._globalDiv.appendChild(this._logDiv);
  29687. this._globalDiv.appendChild(this._optionsDiv);
  29688. this._globalDiv.appendChild(this._treeDiv);
  29689. }
  29690. };
  29691. DebugLayer.prototype._displayStats = function () {
  29692. var scene = this._scene;
  29693. var engine = scene.getEngine();
  29694. var glInfo = engine.getGlInfo();
  29695. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29696. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29697. + "<b>Count</b><br>"
  29698. + "Total meshes: " + scene.meshes.length + "<br>"
  29699. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29700. + "Total materials: " + scene.materials.length + "<br>"
  29701. + "Total textures: " + scene.textures.length + "<br>"
  29702. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29703. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29704. + "Active bones: " + scene.getActiveBones() + "<br>"
  29705. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29706. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  29707. + "<b>Duration</b><br>"
  29708. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29709. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29710. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29711. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29712. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29713. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29714. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  29715. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  29716. + "</div>"
  29717. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29718. + "<b>Extensions</b><br>"
  29719. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29720. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29721. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29722. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  29723. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29724. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  29725. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  29726. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  29727. + "</div><br>"
  29728. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29729. + "<b>Caps.</b><br>"
  29730. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29731. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29732. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  29733. + "<b>Info</b><br>"
  29734. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  29735. + glInfo.version + "<br>"
  29736. + "</div><br>"
  29737. + glInfo.renderer + "<br>";
  29738. if (this.customStatsFunction) {
  29739. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29740. }
  29741. };
  29742. return DebugLayer;
  29743. })();
  29744. BABYLON.DebugLayer = DebugLayer;
  29745. })(BABYLON || (BABYLON = {}));
  29746. var BABYLON;
  29747. (function (BABYLON) {
  29748. var DefaultLoadingScreen = (function () {
  29749. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  29750. var _this = this;
  29751. if (_loadingText === void 0) { _loadingText = ""; }
  29752. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  29753. this._renderingCanvas = _renderingCanvas;
  29754. this._loadingText = _loadingText;
  29755. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  29756. // Resize
  29757. this._resizeLoadingUI = function () {
  29758. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  29759. _this._loadingDiv.style.position = "absolute";
  29760. _this._loadingDiv.style.left = canvasRect.left + "px";
  29761. _this._loadingDiv.style.top = canvasRect.top + "px";
  29762. _this._loadingDiv.style.width = canvasRect.width + "px";
  29763. _this._loadingDiv.style.height = canvasRect.height + "px";
  29764. };
  29765. }
  29766. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  29767. var _this = this;
  29768. if (this._loadingDiv) {
  29769. // Do not add a loading screen if there is already one
  29770. return;
  29771. }
  29772. this._loadingDiv = document.createElement("div");
  29773. this._loadingDiv.id = "babylonjsLoadingDiv";
  29774. this._loadingDiv.style.opacity = "0";
  29775. this._loadingDiv.style.transition = "opacity 1.5s ease";
  29776. // Loading text
  29777. this._loadingTextDiv = document.createElement("div");
  29778. this._loadingTextDiv.style.position = "absolute";
  29779. this._loadingTextDiv.style.left = "0";
  29780. this._loadingTextDiv.style.top = "50%";
  29781. this._loadingTextDiv.style.marginTop = "80px";
  29782. this._loadingTextDiv.style.width = "100%";
  29783. this._loadingTextDiv.style.height = "20px";
  29784. this._loadingTextDiv.style.fontFamily = "Arial";
  29785. this._loadingTextDiv.style.fontSize = "14px";
  29786. this._loadingTextDiv.style.color = "white";
  29787. this._loadingTextDiv.style.textAlign = "center";
  29788. this._loadingTextDiv.innerHTML = "Loading";
  29789. this._loadingDiv.appendChild(this._loadingTextDiv);
  29790. //set the predefined text
  29791. this._loadingTextDiv.innerHTML = this._loadingText;
  29792. // Loading img
  29793. var imgBack = new Image();
  29794. 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==";
  29795. imgBack.style.position = "absolute";
  29796. imgBack.style.left = "50%";
  29797. imgBack.style.top = "50%";
  29798. imgBack.style.marginLeft = "-50px";
  29799. imgBack.style.marginTop = "-50px";
  29800. imgBack.style.transition = "transform 1.0s ease";
  29801. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  29802. var deg = 360;
  29803. var onTransitionEnd = function () {
  29804. deg += 360;
  29805. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  29806. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  29807. };
  29808. imgBack.addEventListener("transitionend", onTransitionEnd);
  29809. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  29810. this._loadingDiv.appendChild(imgBack);
  29811. // front image
  29812. var imgFront = new Image();
  29813. 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=";
  29814. imgFront.style.position = "absolute";
  29815. imgFront.style.left = "50%";
  29816. imgFront.style.top = "50%";
  29817. imgFront.style.marginLeft = "-50px";
  29818. imgFront.style.marginTop = "-50px";
  29819. this._loadingDiv.appendChild(imgFront);
  29820. this._resizeLoadingUI();
  29821. window.addEventListener("resize", this._resizeLoadingUI);
  29822. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29823. document.body.appendChild(this._loadingDiv);
  29824. setTimeout(function () {
  29825. _this._loadingDiv.style.opacity = "1";
  29826. imgBack.style.transform = "rotateZ(360deg)";
  29827. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29828. }, 0);
  29829. };
  29830. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29831. var _this = this;
  29832. if (!this._loadingDiv) {
  29833. return;
  29834. }
  29835. var onTransitionEnd = function () {
  29836. if (!_this._loadingDiv) {
  29837. return;
  29838. }
  29839. document.body.removeChild(_this._loadingDiv);
  29840. window.removeEventListener("resize", _this._resizeLoadingUI);
  29841. _this._loadingDiv = null;
  29842. };
  29843. this._loadingDiv.style.opacity = "0";
  29844. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29845. };
  29846. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29847. set: function (text) {
  29848. this._loadingText = text;
  29849. if (this._loadingTextDiv) {
  29850. this._loadingTextDiv.innerHTML = this._loadingText;
  29851. }
  29852. },
  29853. enumerable: true,
  29854. configurable: true
  29855. });
  29856. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  29857. get: function () {
  29858. return this._loadingDivBackgroundColor;
  29859. },
  29860. set: function (color) {
  29861. this._loadingDivBackgroundColor = color;
  29862. if (!this._loadingDiv) {
  29863. return;
  29864. }
  29865. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29866. },
  29867. enumerable: true,
  29868. configurable: true
  29869. });
  29870. return DefaultLoadingScreen;
  29871. })();
  29872. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  29873. })(BABYLON || (BABYLON = {}));
  29874. var BABYLON;
  29875. (function (BABYLON) {
  29876. var SIMDVector3 = (function () {
  29877. function SIMDVector3() {
  29878. }
  29879. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  29880. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  29881. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29882. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29883. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29884. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29885. 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));
  29886. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29887. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29888. };
  29889. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  29890. var v0 = SIMD.float32x4.splat(x);
  29891. var v1 = SIMD.float32x4.splat(y);
  29892. var v2 = SIMD.float32x4.splat(z);
  29893. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29894. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29895. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29896. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29897. 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));
  29898. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29899. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29900. };
  29901. return SIMDVector3;
  29902. })();
  29903. BABYLON.SIMDVector3 = SIMDVector3;
  29904. var SIMDMatrix = (function () {
  29905. function SIMDMatrix() {
  29906. }
  29907. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  29908. if (offset === void 0) { offset = 0; }
  29909. var tm = this.m;
  29910. var om = other.m;
  29911. var om0 = SIMD.float32x4.load(om, 0);
  29912. var om1 = SIMD.float32x4.load(om, 4);
  29913. var om2 = SIMD.float32x4.load(om, 8);
  29914. var om3 = SIMD.float32x4.load(om, 12);
  29915. var tm0 = SIMD.float32x4.load(tm, 0);
  29916. 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)))));
  29917. var tm1 = SIMD.float32x4.load(tm, 4);
  29918. 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)))));
  29919. var tm2 = SIMD.float32x4.load(tm, 8);
  29920. 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)))));
  29921. var tm3 = SIMD.float32x4.load(tm, 12);
  29922. 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)))));
  29923. };
  29924. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  29925. var src = this.m;
  29926. var dest = other.m;
  29927. var row0, row1, row2, row3;
  29928. var tmp1;
  29929. var minor0, minor1, minor2, minor3;
  29930. var det;
  29931. // Load the 4 rows
  29932. var src0 = SIMD.float32x4.load(src, 0);
  29933. var src1 = SIMD.float32x4.load(src, 4);
  29934. var src2 = SIMD.float32x4.load(src, 8);
  29935. var src3 = SIMD.float32x4.load(src, 12);
  29936. // Transpose the source matrix. Sort of. Not a true transpose operation
  29937. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29938. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29939. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  29940. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  29941. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29942. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29943. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  29944. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  29945. // This is a true transposition, but it will lead to an incorrect result
  29946. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29947. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29948. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29949. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29950. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29951. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29952. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29953. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29954. // ----
  29955. tmp1 = SIMD.float32x4.mul(row2, row3);
  29956. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29957. minor0 = SIMD.float32x4.mul(row1, tmp1);
  29958. minor1 = SIMD.float32x4.mul(row0, tmp1);
  29959. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29960. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  29961. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  29962. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  29963. // ----
  29964. tmp1 = SIMD.float32x4.mul(row1, row2);
  29965. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29966. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  29967. minor3 = SIMD.float32x4.mul(row0, tmp1);
  29968. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29969. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  29970. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  29971. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  29972. // ----
  29973. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  29974. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29975. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  29976. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  29977. minor2 = SIMD.float32x4.mul(row0, tmp1);
  29978. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29979. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  29980. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  29981. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  29982. // ----
  29983. tmp1 = SIMD.float32x4.mul(row0, row1);
  29984. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29985. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  29986. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  29987. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29988. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  29989. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  29990. // ----
  29991. tmp1 = SIMD.float32x4.mul(row0, row3);
  29992. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29993. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  29994. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  29995. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29996. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  29997. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  29998. // ----
  29999. tmp1 = SIMD.float32x4.mul(row0, row2);
  30000. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30001. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  30002. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  30003. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30004. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  30005. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  30006. // Compute determinant
  30007. det = SIMD.float32x4.mul(row0, minor0);
  30008. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  30009. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  30010. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  30011. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  30012. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  30013. // These shuffles aren't necessary if the faulty transposition is done
  30014. // up at the top of this function.
  30015. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  30016. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  30017. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  30018. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  30019. // Compute final values by multiplying with 1/det
  30020. minor0 = SIMD.float32x4.mul(det, minor0);
  30021. minor1 = SIMD.float32x4.mul(det, minor1);
  30022. minor2 = SIMD.float32x4.mul(det, minor2);
  30023. minor3 = SIMD.float32x4.mul(det, minor3);
  30024. SIMD.float32x4.store(dest, 0, minor0);
  30025. SIMD.float32x4.store(dest, 4, minor1);
  30026. SIMD.float32x4.store(dest, 8, minor2);
  30027. SIMD.float32x4.store(dest, 12, minor3);
  30028. return this;
  30029. };
  30030. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  30031. var out = result.m;
  30032. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  30033. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  30034. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  30035. // cc.kmVec3Subtract(f, pCenter, pEye);
  30036. var f = SIMD.float32x4.sub(center, eye);
  30037. // cc.kmVec3Normalize(f, f);
  30038. var tmp = SIMD.float32x4.mul(f, f);
  30039. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30040. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30041. // cc.kmVec3Assign(up, pUp);
  30042. // cc.kmVec3Normalize(up, up);
  30043. tmp = SIMD.float32x4.mul(up, up);
  30044. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30045. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30046. // cc.kmVec3Cross(s, f, up);
  30047. 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)));
  30048. // cc.kmVec3Normalize(s, s);
  30049. tmp = SIMD.float32x4.mul(s, s);
  30050. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30051. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30052. // cc.kmVec3Cross(u, s, f);
  30053. 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)));
  30054. // cc.kmVec3Normalize(s, s);
  30055. tmp = SIMD.float32x4.mul(s, s);
  30056. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30057. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30058. var zero = SIMD.float32x4.splat(0.0);
  30059. s = SIMD.float32x4.neg(s);
  30060. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  30061. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  30062. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30063. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  30064. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  30065. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  30066. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30067. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  30068. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  30069. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  30070. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  30071. var b3 = SIMD.float32x4.neg(eye);
  30072. b3 = SIMD.float32x4.withW(b3, 1.0);
  30073. 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)))));
  30074. 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)))));
  30075. 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)))));
  30076. 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)))));
  30077. };
  30078. return SIMDMatrix;
  30079. })();
  30080. BABYLON.SIMDMatrix = SIMDMatrix;
  30081. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  30082. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  30083. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  30084. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  30085. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  30086. var SIMDHelper = (function () {
  30087. function SIMDHelper() {
  30088. }
  30089. Object.defineProperty(SIMDHelper, "IsEnabled", {
  30090. get: function () {
  30091. return SIMDHelper._isEnabled;
  30092. },
  30093. enumerable: true,
  30094. configurable: true
  30095. });
  30096. SIMDHelper.DisableSIMD = function () {
  30097. // Replace functions
  30098. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  30099. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  30100. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  30101. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  30102. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  30103. SIMDHelper._isEnabled = false;
  30104. };
  30105. SIMDHelper.EnableSIMD = function () {
  30106. if (window.SIMD === undefined) {
  30107. return;
  30108. }
  30109. // Replace functions
  30110. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  30111. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  30112. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  30113. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  30114. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  30115. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  30116. get: function () { return this._data[0]; },
  30117. set: function (value) {
  30118. if (!this._data) {
  30119. this._data = new Float32Array(3);
  30120. }
  30121. this._data[0] = value;
  30122. }
  30123. });
  30124. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  30125. get: function () { return this._data[1]; },
  30126. set: function (value) {
  30127. this._data[1] = value;
  30128. }
  30129. });
  30130. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  30131. get: function () { return this._data[2]; },
  30132. set: function (value) {
  30133. this._data[2] = value;
  30134. }
  30135. });
  30136. SIMDHelper._isEnabled = true;
  30137. };
  30138. SIMDHelper._isEnabled = false;
  30139. return SIMDHelper;
  30140. })();
  30141. BABYLON.SIMDHelper = SIMDHelper;
  30142. })(BABYLON || (BABYLON = {}));
  30143. var BABYLON;
  30144. (function (BABYLON) {
  30145. var ShaderMaterial = (function (_super) {
  30146. __extends(ShaderMaterial, _super);
  30147. function ShaderMaterial(name, scene, shaderPath, options) {
  30148. _super.call(this, name, scene);
  30149. this._textures = {};
  30150. this._floats = {};
  30151. this._floatsArrays = {};
  30152. this._colors3 = {};
  30153. this._colors4 = {};
  30154. this._vectors2 = {};
  30155. this._vectors3 = {};
  30156. this._vectors4 = {};
  30157. this._matrices = {};
  30158. this._matrices3x3 = {};
  30159. this._matrices2x2 = {};
  30160. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  30161. this._shaderPath = shaderPath;
  30162. options.needAlphaBlending = options.needAlphaBlending || false;
  30163. options.needAlphaTesting = options.needAlphaTesting || false;
  30164. options.attributes = options.attributes || ["position", "normal", "uv"];
  30165. options.uniforms = options.uniforms || ["worldViewProjection"];
  30166. options.samplers = options.samplers || [];
  30167. options.defines = options.defines || [];
  30168. this._options = options;
  30169. }
  30170. ShaderMaterial.prototype.needAlphaBlending = function () {
  30171. return this._options.needAlphaBlending;
  30172. };
  30173. ShaderMaterial.prototype.needAlphaTesting = function () {
  30174. return this._options.needAlphaTesting;
  30175. };
  30176. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  30177. if (this._options.uniforms.indexOf(uniformName) === -1) {
  30178. this._options.uniforms.push(uniformName);
  30179. }
  30180. };
  30181. ShaderMaterial.prototype.setTexture = function (name, texture) {
  30182. if (this._options.samplers.indexOf(name) === -1) {
  30183. this._options.samplers.push(name);
  30184. }
  30185. this._textures[name] = texture;
  30186. return this;
  30187. };
  30188. ShaderMaterial.prototype.setFloat = function (name, value) {
  30189. this._checkUniform(name);
  30190. this._floats[name] = value;
  30191. return this;
  30192. };
  30193. ShaderMaterial.prototype.setFloats = function (name, value) {
  30194. this._checkUniform(name);
  30195. this._floatsArrays[name] = value;
  30196. return this;
  30197. };
  30198. ShaderMaterial.prototype.setColor3 = function (name, value) {
  30199. this._checkUniform(name);
  30200. this._colors3[name] = value;
  30201. return this;
  30202. };
  30203. ShaderMaterial.prototype.setColor4 = function (name, value) {
  30204. this._checkUniform(name);
  30205. this._colors4[name] = value;
  30206. return this;
  30207. };
  30208. ShaderMaterial.prototype.setVector2 = function (name, value) {
  30209. this._checkUniform(name);
  30210. this._vectors2[name] = value;
  30211. return this;
  30212. };
  30213. ShaderMaterial.prototype.setVector3 = function (name, value) {
  30214. this._checkUniform(name);
  30215. this._vectors3[name] = value;
  30216. return this;
  30217. };
  30218. ShaderMaterial.prototype.setVector4 = function (name, value) {
  30219. this._checkUniform(name);
  30220. this._vectors4[name] = value;
  30221. return this;
  30222. };
  30223. ShaderMaterial.prototype.setMatrix = function (name, value) {
  30224. this._checkUniform(name);
  30225. this._matrices[name] = value;
  30226. return this;
  30227. };
  30228. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  30229. this._checkUniform(name);
  30230. this._matrices3x3[name] = value;
  30231. return this;
  30232. };
  30233. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  30234. this._checkUniform(name);
  30235. this._matrices2x2[name] = value;
  30236. return this;
  30237. };
  30238. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  30239. var scene = this.getScene();
  30240. var engine = scene.getEngine();
  30241. if (!this.checkReadyOnEveryCall) {
  30242. if (this._renderId === scene.getRenderId()) {
  30243. return true;
  30244. }
  30245. }
  30246. // Instances
  30247. var defines = [];
  30248. var fallbacks = new BABYLON.EffectFallbacks();
  30249. if (useInstances) {
  30250. defines.push("#define INSTANCES");
  30251. }
  30252. for (var index = 0; index < this._options.defines.length; index++) {
  30253. defines.push(this._options.defines[index]);
  30254. }
  30255. // Bones
  30256. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30257. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  30258. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30259. fallbacks.addCPUSkinningFallback(0, mesh);
  30260. }
  30261. // Alpha test
  30262. if (engine.getAlphaTesting()) {
  30263. defines.push("#define ALPHATEST");
  30264. }
  30265. var previousEffect = this._effect;
  30266. var join = defines.join("\n");
  30267. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  30268. if (!this._effect.isReady()) {
  30269. return false;
  30270. }
  30271. if (previousEffect !== this._effect) {
  30272. scene.resetCachedMaterial();
  30273. }
  30274. this._renderId = scene.getRenderId();
  30275. return true;
  30276. };
  30277. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30278. var scene = this.getScene();
  30279. if (this._options.uniforms.indexOf("world") !== -1) {
  30280. this._effect.setMatrix("world", world);
  30281. }
  30282. if (this._options.uniforms.indexOf("worldView") !== -1) {
  30283. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  30284. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  30285. }
  30286. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  30287. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  30288. }
  30289. };
  30290. ShaderMaterial.prototype.bind = function (world, mesh) {
  30291. // Std values
  30292. this.bindOnlyWorldMatrix(world);
  30293. if (this.getScene().getCachedMaterial() !== this) {
  30294. if (this._options.uniforms.indexOf("view") !== -1) {
  30295. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  30296. }
  30297. if (this._options.uniforms.indexOf("projection") !== -1) {
  30298. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  30299. }
  30300. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  30301. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30302. }
  30303. // Bones
  30304. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30305. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  30306. }
  30307. // Texture
  30308. for (var name in this._textures) {
  30309. this._effect.setTexture(name, this._textures[name]);
  30310. }
  30311. // Float
  30312. for (name in this._floats) {
  30313. this._effect.setFloat(name, this._floats[name]);
  30314. }
  30315. // Float s
  30316. for (name in this._floatsArrays) {
  30317. this._effect.setArray(name, this._floatsArrays[name]);
  30318. }
  30319. // Color3
  30320. for (name in this._colors3) {
  30321. this._effect.setColor3(name, this._colors3[name]);
  30322. }
  30323. // Color4
  30324. for (name in this._colors4) {
  30325. var color = this._colors4[name];
  30326. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  30327. }
  30328. // Vector2
  30329. for (name in this._vectors2) {
  30330. this._effect.setVector2(name, this._vectors2[name]);
  30331. }
  30332. // Vector3
  30333. for (name in this._vectors3) {
  30334. this._effect.setVector3(name, this._vectors3[name]);
  30335. }
  30336. // Vector4
  30337. for (name in this._vectors4) {
  30338. this._effect.setVector4(name, this._vectors4[name]);
  30339. }
  30340. // Matrix
  30341. for (name in this._matrices) {
  30342. this._effect.setMatrix(name, this._matrices[name]);
  30343. }
  30344. // Matrix 3x3
  30345. for (name in this._matrices3x3) {
  30346. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  30347. }
  30348. // Matrix 2x2
  30349. for (name in this._matrices2x2) {
  30350. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  30351. }
  30352. }
  30353. _super.prototype.bind.call(this, world, mesh);
  30354. };
  30355. ShaderMaterial.prototype.clone = function (name) {
  30356. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  30357. return newShaderMaterial;
  30358. };
  30359. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  30360. for (var name in this._textures) {
  30361. this._textures[name].dispose();
  30362. }
  30363. this._textures = {};
  30364. _super.prototype.dispose.call(this, forceDisposeEffect);
  30365. };
  30366. ShaderMaterial.prototype.serialize = function () {
  30367. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30368. serializationObject.customType = "BABYLON.ShaderMaterial";
  30369. serializationObject.options = this._options;
  30370. serializationObject.shaderPath = this._shaderPath;
  30371. // Texture
  30372. serializationObject.textures = {};
  30373. for (var name in this._textures) {
  30374. serializationObject.textures[name] = this._textures[name].serialize();
  30375. }
  30376. // Float
  30377. serializationObject.floats = {};
  30378. for (name in this._floats) {
  30379. serializationObject.floats[name] = this._floats[name];
  30380. }
  30381. // Float s
  30382. serializationObject.floatArrays = {};
  30383. for (name in this._floatsArrays) {
  30384. serializationObject.floatArrays[name] = this._floatsArrays[name];
  30385. }
  30386. // Color3
  30387. serializationObject.colors3 = {};
  30388. for (name in this._colors3) {
  30389. serializationObject.colors3[name] = this._colors3[name].asArray();
  30390. }
  30391. // Color4
  30392. serializationObject.colors4 = {};
  30393. for (name in this._colors4) {
  30394. serializationObject.colors4[name] = this._colors4[name].asArray();
  30395. }
  30396. // Vector2
  30397. serializationObject.vectors2 = {};
  30398. for (name in this._vectors2) {
  30399. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  30400. }
  30401. // Vector3
  30402. serializationObject.vectors3 = {};
  30403. for (name in this._vectors3) {
  30404. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  30405. }
  30406. // Vector4
  30407. serializationObject.vectors4 = {};
  30408. for (name in this._vectors4) {
  30409. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  30410. }
  30411. // Matrix
  30412. serializationObject.matrices = {};
  30413. for (name in this._matrices) {
  30414. serializationObject.matrices[name] = this._matrices[name].asArray();
  30415. }
  30416. // Matrix 3x3
  30417. serializationObject.matrices3x3 = {};
  30418. for (name in this._matrices3x3) {
  30419. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  30420. }
  30421. // Matrix 2x2
  30422. serializationObject.matrices2x2 = {};
  30423. for (name in this._matrices2x2) {
  30424. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  30425. }
  30426. return serializationObject;
  30427. };
  30428. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  30429. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  30430. // Texture
  30431. for (var name in source.textures) {
  30432. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  30433. }
  30434. // Float
  30435. for (name in source.floats) {
  30436. material.setFloat(name, source.floats[name]);
  30437. }
  30438. // Float s
  30439. for (name in source.floatsArrays) {
  30440. material.setFloats(name, source.floatsArrays[name]);
  30441. }
  30442. // Color3
  30443. for (name in source.colors3) {
  30444. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  30445. }
  30446. // Color4
  30447. for (name in source.colors4) {
  30448. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  30449. }
  30450. // Vector2
  30451. for (name in source.vectors2) {
  30452. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  30453. }
  30454. // Vector3
  30455. for (name in source.vectors3) {
  30456. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  30457. }
  30458. // Vector4
  30459. for (name in source.vectors4) {
  30460. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  30461. }
  30462. // Matrix
  30463. for (name in source.matrices) {
  30464. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  30465. }
  30466. // Matrix 3x3
  30467. for (name in source.matrices3x3) {
  30468. material.setMatrix3x3(name, source.matrices3x3[name]);
  30469. }
  30470. // Matrix 2x2
  30471. for (name in source.matrices2x2) {
  30472. material.setMatrix2x2(name, source.matrices2x2[name]);
  30473. }
  30474. return material;
  30475. };
  30476. return ShaderMaterial;
  30477. })(BABYLON.Material);
  30478. BABYLON.ShaderMaterial = ShaderMaterial;
  30479. })(BABYLON || (BABYLON = {}));
  30480. var BABYLON;
  30481. (function (BABYLON) {
  30482. var Internals;
  30483. (function (Internals) {
  30484. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  30485. // All values and structures referenced from:
  30486. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  30487. var DDS_MAGIC = 0x20534444;
  30488. 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;
  30489. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  30490. 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;
  30491. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  30492. function FourCCToInt32(value) {
  30493. return value.charCodeAt(0) +
  30494. (value.charCodeAt(1) << 8) +
  30495. (value.charCodeAt(2) << 16) +
  30496. (value.charCodeAt(3) << 24);
  30497. }
  30498. function Int32ToFourCC(value) {
  30499. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  30500. }
  30501. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  30502. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  30503. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  30504. var headerLengthInt = 31; // The header length in 32 bit ints
  30505. // Offsets into the header array
  30506. var off_magic = 0;
  30507. var off_size = 1;
  30508. var off_flags = 2;
  30509. var off_height = 3;
  30510. var off_width = 4;
  30511. var off_mipmapCount = 7;
  30512. var off_pfFlags = 20;
  30513. var off_pfFourCC = 21;
  30514. var off_RGBbpp = 22;
  30515. var off_RMask = 23;
  30516. var off_GMask = 24;
  30517. var off_BMask = 25;
  30518. var off_AMask = 26;
  30519. var off_caps1 = 27;
  30520. var off_caps2 = 28;
  30521. ;
  30522. var DDSTools = (function () {
  30523. function DDSTools() {
  30524. }
  30525. DDSTools.GetDDSInfo = function (arrayBuffer) {
  30526. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  30527. var mipmapCount = 1;
  30528. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  30529. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30530. }
  30531. return {
  30532. width: header[off_width],
  30533. height: header[off_height],
  30534. mipmapCount: mipmapCount,
  30535. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  30536. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  30537. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  30538. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  30539. };
  30540. };
  30541. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30542. var byteArray = new Uint8Array(dataLength);
  30543. var srcData = new Uint8Array(arrayBuffer);
  30544. var index = 0;
  30545. for (var y = height - 1; y >= 0; y--) {
  30546. for (var x = 0; x < width; x++) {
  30547. var srcPos = dataOffset + (x + y * width) * 4;
  30548. byteArray[index + 2] = srcData[srcPos];
  30549. byteArray[index + 1] = srcData[srcPos + 1];
  30550. byteArray[index] = srcData[srcPos + 2];
  30551. byteArray[index + 3] = srcData[srcPos + 3];
  30552. index += 4;
  30553. }
  30554. }
  30555. return byteArray;
  30556. };
  30557. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30558. var byteArray = new Uint8Array(dataLength);
  30559. var srcData = new Uint8Array(arrayBuffer);
  30560. var index = 0;
  30561. for (var y = height - 1; y >= 0; y--) {
  30562. for (var x = 0; x < width; x++) {
  30563. var srcPos = dataOffset + (x + y * width) * 3;
  30564. byteArray[index + 2] = srcData[srcPos];
  30565. byteArray[index + 1] = srcData[srcPos + 1];
  30566. byteArray[index] = srcData[srcPos + 2];
  30567. index += 3;
  30568. }
  30569. }
  30570. return byteArray;
  30571. };
  30572. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30573. var byteArray = new Uint8Array(dataLength);
  30574. var srcData = new Uint8Array(arrayBuffer);
  30575. var index = 0;
  30576. for (var y = height - 1; y >= 0; y--) {
  30577. for (var x = 0; x < width; x++) {
  30578. var srcPos = dataOffset + (x + y * width);
  30579. byteArray[index] = srcData[srcPos];
  30580. index++;
  30581. }
  30582. }
  30583. return byteArray;
  30584. };
  30585. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  30586. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  30587. if (header[off_magic] != DDS_MAGIC) {
  30588. BABYLON.Tools.Error("Invalid magic number in DDS header");
  30589. return;
  30590. }
  30591. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  30592. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  30593. return;
  30594. }
  30595. if (info.isFourCC) {
  30596. fourCC = header[off_pfFourCC];
  30597. switch (fourCC) {
  30598. case FOURCC_DXT1:
  30599. blockBytes = 8;
  30600. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  30601. break;
  30602. case FOURCC_DXT3:
  30603. blockBytes = 16;
  30604. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  30605. break;
  30606. case FOURCC_DXT5:
  30607. blockBytes = 16;
  30608. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  30609. break;
  30610. default:
  30611. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  30612. return;
  30613. }
  30614. }
  30615. mipmapCount = 1;
  30616. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  30617. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30618. }
  30619. var bpp = header[off_RGBbpp];
  30620. for (var face = 0; face < faces; face++) {
  30621. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  30622. width = header[off_width];
  30623. height = header[off_height];
  30624. dataOffset = header[off_size] + 4;
  30625. for (i = 0; i < mipmapCount; ++i) {
  30626. if (info.isRGB) {
  30627. if (bpp === 24) {
  30628. dataLength = width * height * 3;
  30629. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30630. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  30631. }
  30632. else {
  30633. dataLength = width * height * 4;
  30634. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30635. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  30636. }
  30637. }
  30638. else if (info.isLuminance) {
  30639. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  30640. var unpaddedRowSize = width;
  30641. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  30642. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  30643. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30644. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  30645. }
  30646. else {
  30647. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  30648. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  30649. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  30650. }
  30651. dataOffset += dataLength;
  30652. width *= 0.5;
  30653. height *= 0.5;
  30654. width = Math.max(1.0, width);
  30655. height = Math.max(1.0, height);
  30656. }
  30657. }
  30658. };
  30659. return DDSTools;
  30660. })();
  30661. Internals.DDSTools = DDSTools;
  30662. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30663. })(BABYLON || (BABYLON = {}));
  30664. var BABYLON;
  30665. (function (BABYLON) {
  30666. var CannonJSPlugin = (function () {
  30667. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  30668. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  30669. if (iterations === void 0) { iterations = 10; }
  30670. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  30671. this.name = "CannonJSPlugin";
  30672. this._physicsMaterials = [];
  30673. this._fixedTimeStep = 1 / 60;
  30674. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30675. this._currentCollisionGroup = 2;
  30676. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30677. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30678. this._tmpPosition = BABYLON.Vector3.Zero();
  30679. this._tmpQuaternion = new BABYLON.Quaternion();
  30680. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  30681. this._tmpDeltaRotation = new BABYLON.Quaternion();
  30682. this._tmpUnityRotation = new BABYLON.Quaternion();
  30683. if (!this.isSupported()) {
  30684. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  30685. return;
  30686. }
  30687. this.world = new CANNON.World();
  30688. this.world.broadphase = new CANNON.NaiveBroadphase();
  30689. this.world.solver.iterations = iterations;
  30690. }
  30691. CannonJSPlugin.prototype.setGravity = function (gravity) {
  30692. this.world.gravity.copy(gravity);
  30693. };
  30694. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  30695. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  30696. };
  30697. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  30698. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30699. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30700. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30701. };
  30702. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  30703. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30704. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30705. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30706. };
  30707. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  30708. //parent-child relationship. Does this impostor has a parent impostor?
  30709. if (impostor.parent) {
  30710. if (impostor.physicsBody) {
  30711. this.removePhysicsBody(impostor);
  30712. //TODO is that needed?
  30713. impostor.forceUpdate();
  30714. }
  30715. return;
  30716. }
  30717. //should a new body be created for this impostor?
  30718. if (impostor.isBodyInitRequired()) {
  30719. if (!impostor.mesh.rotationQuaternion) {
  30720. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  30721. }
  30722. var shape = this._createShape(impostor);
  30723. //unregister events, if body is being changed
  30724. var oldBody = impostor.physicsBody;
  30725. if (oldBody) {
  30726. this.removePhysicsBody(impostor);
  30727. }
  30728. //create the body and material
  30729. var material = this._addMaterial("mat-" + impostor.mesh.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  30730. var bodyCreationObject = {
  30731. mass: impostor.getParam("mass"),
  30732. material: material
  30733. };
  30734. // A simple extend, in case native options were used.
  30735. var nativeOptions = impostor.getParam("nativeOptions");
  30736. for (var key in nativeOptions) {
  30737. if (nativeOptions.hasOwnProperty(key)) {
  30738. bodyCreationObject[key] = nativeOptions[key];
  30739. }
  30740. }
  30741. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  30742. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  30743. this.world.addEventListener("preStep", impostor.beforeStep);
  30744. this.world.addEventListener("postStep", impostor.afterStep);
  30745. impostor.physicsBody.addShape(shape);
  30746. this.world.add(impostor.physicsBody);
  30747. //try to keep the body moving in the right direction by taking old properties.
  30748. //Should be tested!
  30749. if (oldBody) {
  30750. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  30751. impostor.physicsBody[param].copy(oldBody[param]);
  30752. });
  30753. }
  30754. this._processChildMeshes(impostor);
  30755. }
  30756. //now update the body's transformation
  30757. this._updatePhysicsBodyTransformation(impostor);
  30758. };
  30759. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  30760. var _this = this;
  30761. var meshChildren = mainImpostor.mesh.getChildMeshes();
  30762. if (meshChildren.length) {
  30763. var processMesh = function (localPosition, mesh) {
  30764. var childImpostor = mesh.getPhysicsImpostor();
  30765. if (childImpostor) {
  30766. var parent = childImpostor.parent;
  30767. if (parent !== mainImpostor) {
  30768. var localPosition = mesh.position;
  30769. if (childImpostor.physicsBody) {
  30770. _this.removePhysicsBody(childImpostor);
  30771. childImpostor.physicsBody = null;
  30772. }
  30773. childImpostor.parent = mainImpostor;
  30774. childImpostor.resetUpdateFlags();
  30775. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30776. //Add the mass of the children.
  30777. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  30778. }
  30779. }
  30780. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  30781. };
  30782. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  30783. }
  30784. };
  30785. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  30786. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  30787. this.world.removeEventListener("preStep", impostor.beforeStep);
  30788. this.world.removeEventListener("postStep", impostor.afterStep);
  30789. this.world.remove(impostor.physicsBody);
  30790. };
  30791. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  30792. var mainBody = impostorJoint.mainImpostor.physicsBody;
  30793. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  30794. if (!mainBody || !connectedBody) {
  30795. return;
  30796. }
  30797. var constraint;
  30798. var jointData = impostorJoint.joint.jointData;
  30799. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30800. var constraintData = {
  30801. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  30802. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  30803. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  30804. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  30805. maxForce: jointData.nativeParams.maxForce,
  30806. collideConnected: !!jointData.collision
  30807. };
  30808. //Not needed, Cannon has a collideConnected flag
  30809. /*if (!jointData.collision) {
  30810. //add 1st body to a collision group of its own, if it is not in 1
  30811. if (mainBody.collisionFilterGroup === 1) {
  30812. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  30813. this._currentCollisionGroup <<= 1;
  30814. }
  30815. if (connectedBody.collisionFilterGroup === 1) {
  30816. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  30817. this._currentCollisionGroup <<= 1;
  30818. }
  30819. //add their mask to the collisionFilterMask of each other:
  30820. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  30821. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  30822. }*/
  30823. switch (impostorJoint.joint.type) {
  30824. case BABYLON.PhysicsJoint.HingeJoint:
  30825. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  30826. break;
  30827. case BABYLON.PhysicsJoint.DistanceJoint:
  30828. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  30829. break;
  30830. case BABYLON.PhysicsJoint.SpringJoint:
  30831. var springData = jointData;
  30832. constraint = new CANNON.Spring(mainBody, connectedBody, {
  30833. restLength: springData.length,
  30834. stiffness: springData.stiffness,
  30835. damping: springData.damping,
  30836. localAnchorA: constraintData.pivotA,
  30837. localAnchorB: constraintData.pivotB
  30838. });
  30839. break;
  30840. default:
  30841. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  30842. break;
  30843. }
  30844. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  30845. constraint.collideConnected = !!jointData.collision;
  30846. impostorJoint.joint.physicsJoint = constraint;
  30847. this.world.addConstraint(constraint);
  30848. };
  30849. CannonJSPlugin.prototype.removeJoint = function (joint) {
  30850. //TODO
  30851. };
  30852. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  30853. var index;
  30854. var mat;
  30855. for (index = 0; index < this._physicsMaterials.length; index++) {
  30856. mat = this._physicsMaterials[index];
  30857. if (mat.friction === friction && mat.restitution === restitution) {
  30858. return mat;
  30859. }
  30860. }
  30861. var currentMat = new CANNON.Material("mat");
  30862. currentMat.friction = friction;
  30863. currentMat.restitution = restitution;
  30864. this._physicsMaterials.push(currentMat);
  30865. return currentMat;
  30866. };
  30867. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  30868. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30869. };
  30870. CannonJSPlugin.prototype._createShape = function (impostor) {
  30871. var mesh = impostor.mesh;
  30872. //get the correct bounding box
  30873. var oldQuaternion = mesh.rotationQuaternion;
  30874. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30875. mesh.computeWorldMatrix(true);
  30876. var returnValue;
  30877. switch (impostor.type) {
  30878. case BABYLON.PhysicsEngine.SphereImpostor:
  30879. var bbox = mesh.getBoundingInfo().boundingBox;
  30880. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30881. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30882. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30883. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  30884. break;
  30885. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  30886. case BABYLON.PhysicsEngine.CylinderImpostor:
  30887. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  30888. case BABYLON.PhysicsEngine.BoxImpostor:
  30889. bbox = mesh.getBoundingInfo().boundingBox;
  30890. var min = bbox.minimumWorld;
  30891. var max = bbox.maximumWorld;
  30892. var box = max.subtract(min).scale(0.5);
  30893. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  30894. break;
  30895. case BABYLON.PhysicsEngine.PlaneImpostor:
  30896. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  30897. returnValue = new CANNON.Plane();
  30898. break;
  30899. case BABYLON.PhysicsEngine.MeshImpostor:
  30900. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30901. var rawFaces = mesh.getIndices();
  30902. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  30903. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  30904. break;
  30905. case BABYLON.PhysicsEngine.HeightmapImpostor:
  30906. returnValue = this._createHeightmap(mesh);
  30907. break;
  30908. }
  30909. mesh.rotationQuaternion = oldQuaternion;
  30910. return returnValue;
  30911. };
  30912. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  30913. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30914. var matrix = [];
  30915. //For now pointDepth will not be used and will be automatically calculated.
  30916. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  30917. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  30918. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  30919. var elementSize = dim * 2 / arraySize;
  30920. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  30921. for (var i = 0; i < pos.length; i = i + 3) {
  30922. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  30923. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  30924. var y = pos[i + 1] + minY;
  30925. if (!matrix[x]) {
  30926. matrix[x] = [];
  30927. }
  30928. if (!matrix[x][z]) {
  30929. matrix[x][z] = y;
  30930. }
  30931. matrix[x][z] = Math.max(y, matrix[x][z]);
  30932. }
  30933. for (var x = 0; x <= arraySize; ++x) {
  30934. if (!matrix[x]) {
  30935. var loc = 1;
  30936. while (!matrix[(x + loc) % arraySize]) {
  30937. loc++;
  30938. }
  30939. matrix[x] = matrix[(x + loc) % arraySize].slice();
  30940. }
  30941. for (var z = 0; z <= arraySize; ++z) {
  30942. if (!matrix[x][z]) {
  30943. var loc = 1;
  30944. var newValue;
  30945. while (newValue === undefined) {
  30946. newValue = matrix[x][(z + loc++) % arraySize];
  30947. }
  30948. matrix[x][z] = newValue;
  30949. }
  30950. }
  30951. }
  30952. var shape = new CANNON.Heightfield(matrix, {
  30953. elementSize: elementSize
  30954. });
  30955. //For future reference, needed for body transformation
  30956. shape.minY = minY;
  30957. return shape;
  30958. };
  30959. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  30960. var mesh = impostor.mesh;
  30961. //make sure it is updated...
  30962. impostor.mesh.computeWorldMatrix(true);
  30963. // The delta between the mesh position and the mesh bounding box center
  30964. var bbox = mesh.getBoundingInfo().boundingBox;
  30965. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  30966. var quaternion = mesh.rotationQuaternion;
  30967. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  30968. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  30969. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  30970. //-90 DEG in X, precalculated
  30971. quaternion = quaternion.multiply(this._minus90X);
  30972. //Invert! (Precalculated, 90 deg in X)
  30973. //No need to clone. this will never change.
  30974. impostor.setDeltaRotation(this._plus90X);
  30975. }
  30976. //If it is a heightfield, if should be centered.
  30977. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  30978. //calculate the correct body position:
  30979. var rotationQuaternion = mesh.rotationQuaternion;
  30980. mesh.rotationQuaternion = this._tmpUnityRotation;
  30981. mesh.computeWorldMatrix(true);
  30982. //get original center with no rotation
  30983. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30984. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  30985. //rotation is back
  30986. mesh.rotationQuaternion = rotationQuaternion;
  30987. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  30988. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  30989. mesh.setPivotMatrix(p);
  30990. mesh.computeWorldMatrix(true);
  30991. //calculate the translation
  30992. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  30993. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  30994. //add it inverted to the delta
  30995. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  30996. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  30997. mesh.setPivotMatrix(oldPivot);
  30998. mesh.computeWorldMatrix(true);
  30999. }
  31000. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  31001. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  31002. this._tmpPosition.copyFrom(mesh.position);
  31003. }
  31004. impostor.setDeltaPosition(this._tmpDeltaPosition);
  31005. //Now update the impostor object
  31006. impostor.physicsBody.position.copy(this._tmpPosition);
  31007. impostor.physicsBody.quaternion.copy(quaternion);
  31008. };
  31009. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31010. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  31011. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  31012. };
  31013. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31014. impostor.physicsBody.position.copy(newPosition);
  31015. impostor.physicsBody.quaternion.copy(newRotation);
  31016. };
  31017. CannonJSPlugin.prototype.isSupported = function () {
  31018. return window.CANNON !== undefined;
  31019. };
  31020. CannonJSPlugin.prototype.setVelocity = function (impostor, velocity) {
  31021. impostor.physicsBody.velocity.copy(velocity);
  31022. };
  31023. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  31024. impostor.physicsBody.sleep();
  31025. };
  31026. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  31027. impostor.physicsBody.wakeUp();
  31028. };
  31029. CannonJSPlugin.prototype.dispose = function () {
  31030. //nothing to do, actually.
  31031. };
  31032. return CannonJSPlugin;
  31033. })();
  31034. BABYLON.CannonJSPlugin = CannonJSPlugin;
  31035. })(BABYLON || (BABYLON = {}));
  31036. var BABYLON;
  31037. (function (BABYLON) {
  31038. var OimoJSPlugin = (function () {
  31039. function OimoJSPlugin(iterations) {
  31040. this.name = "OimoJSPlugin";
  31041. this._tmpImpostorsArray = [];
  31042. this._tmpPositionVector = BABYLON.Vector3.Zero();
  31043. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  31044. this.world.clear();
  31045. //making sure no stats are calculated
  31046. this.world.isNoStat = true;
  31047. }
  31048. OimoJSPlugin.prototype.setGravity = function (gravity) {
  31049. this.world.gravity.copy(gravity);
  31050. };
  31051. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  31052. var _this = this;
  31053. impostors.forEach(function (impostor) {
  31054. impostor.beforeStep();
  31055. });
  31056. this.world.step();
  31057. impostors.forEach(function (impostor) {
  31058. impostor.afterStep();
  31059. //update the ordered impostors array
  31060. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  31061. });
  31062. //check for collisions
  31063. var contact = this.world.contacts;
  31064. while (contact !== null) {
  31065. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  31066. contact = contact.next;
  31067. continue;
  31068. }
  31069. //is this body colliding with any other? get the impostor
  31070. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  31071. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  31072. if (!mainImpostor || !collidingImpostor) {
  31073. contact = contact.next;
  31074. continue;
  31075. }
  31076. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  31077. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  31078. contact = contact.next;
  31079. }
  31080. };
  31081. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  31082. var mass = impostor.physicsBody.massInfo.mass;
  31083. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  31084. };
  31085. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  31086. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  31087. this.applyImpulse(impostor, force, contactPoint);
  31088. };
  31089. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  31090. var _this = this;
  31091. //parent-child relationship. Does this impostor has a parent impostor?
  31092. if (impostor.parent) {
  31093. if (impostor.physicsBody) {
  31094. this.removePhysicsBody(impostor);
  31095. //TODO is that needed?
  31096. impostor.forceUpdate();
  31097. }
  31098. return;
  31099. }
  31100. impostor.mesh.computeWorldMatrix(true);
  31101. if (impostor.isBodyInitRequired()) {
  31102. if (!impostor.mesh.rotationQuaternion) {
  31103. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  31104. }
  31105. var bodyConfig = {
  31106. name: impostor.mesh.uniqueId,
  31107. //Oimo must have mass, also for static objects.
  31108. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  31109. size: [],
  31110. type: [],
  31111. pos: [],
  31112. rot: [],
  31113. move: impostor.getParam("mass") !== 0,
  31114. //Supporting older versions of Oimo
  31115. world: this.world
  31116. };
  31117. var impostors = [impostor];
  31118. function addToArray(parent) {
  31119. parent.getChildMeshes().forEach(function (m) {
  31120. if (m.physicsImpostor) {
  31121. impostors.push(m.physicsImpostor);
  31122. m.physicsImpostor._init();
  31123. }
  31124. });
  31125. }
  31126. addToArray(impostor.mesh);
  31127. function checkWithEpsilon(value) {
  31128. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  31129. }
  31130. impostors.forEach(function (i) {
  31131. //get the correct bounding box
  31132. var oldQuaternion = i.mesh.rotationQuaternion;
  31133. var rot = new OIMO.Euler().setFromQuaternion({ x: impostor.mesh.rotationQuaternion.x, y: impostor.mesh.rotationQuaternion.y, z: impostor.mesh.rotationQuaternion.z, s: impostor.mesh.rotationQuaternion.w });
  31134. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31135. i.mesh.computeWorldMatrix(true);
  31136. var bbox = i.mesh.getBoundingInfo().boundingBox;
  31137. if (i === impostor) {
  31138. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  31139. //Can also use Array.prototype.push.apply
  31140. bodyConfig.pos.push(bbox.center.x);
  31141. bodyConfig.pos.push(bbox.center.y);
  31142. bodyConfig.pos.push(bbox.center.z);
  31143. //tmp solution
  31144. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  31145. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  31146. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  31147. }
  31148. else {
  31149. bodyConfig.pos.push(i.mesh.position.x);
  31150. bodyConfig.pos.push(i.mesh.position.y);
  31151. bodyConfig.pos.push(i.mesh.position.z);
  31152. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  31153. bodyConfig.rot.push(0);
  31154. bodyConfig.rot.push(0);
  31155. bodyConfig.rot.push(0);
  31156. }
  31157. // register mesh
  31158. switch (i.type) {
  31159. case BABYLON.PhysicsEngine.SphereImpostor:
  31160. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31161. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31162. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31163. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  31164. bodyConfig.type.push('sphere');
  31165. //due to the way oimo works with compounds, add 3 times
  31166. bodyConfig.size.push(size);
  31167. bodyConfig.size.push(size);
  31168. bodyConfig.size.push(size);
  31169. break;
  31170. case BABYLON.PhysicsEngine.PlaneImpostor:
  31171. //TODO Oimo now supports cylinder!
  31172. case BABYLON.PhysicsEngine.CylinderImpostor:
  31173. case BABYLON.PhysicsEngine.BoxImpostor:
  31174. default:
  31175. var min = bbox.minimumWorld;
  31176. var max = bbox.maximumWorld;
  31177. var box = max.subtract(min);
  31178. var sizeX = checkWithEpsilon(box.x);
  31179. var sizeY = checkWithEpsilon(box.y);
  31180. var sizeZ = checkWithEpsilon(box.z);
  31181. bodyConfig.type.push('box');
  31182. bodyConfig.size.push(sizeX);
  31183. bodyConfig.size.push(sizeY);
  31184. bodyConfig.size.push(sizeZ);
  31185. break;
  31186. }
  31187. //actually not needed, but hey...
  31188. i.mesh.rotationQuaternion = oldQuaternion;
  31189. });
  31190. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  31191. }
  31192. else {
  31193. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  31194. }
  31195. impostor.setDeltaPosition(this._tmpPositionVector);
  31196. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  31197. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  31198. };
  31199. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  31200. //impostor.physicsBody.dispose();
  31201. //Same as : (older oimo versions)
  31202. this.world.removeRigidBody(impostor.physicsBody);
  31203. };
  31204. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  31205. var mainBody = impostorJoint.mainImpostor.physicsBody;
  31206. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  31207. if (!mainBody || !connectedBody) {
  31208. return;
  31209. }
  31210. var jointData = impostorJoint.joint.jointData;
  31211. var options = jointData.nativeParams || {};
  31212. var type;
  31213. var nativeJointData = {
  31214. body1: mainBody,
  31215. body2: connectedBody,
  31216. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  31217. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  31218. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  31219. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  31220. min: options.min,
  31221. max: options.max,
  31222. collision: options.collision || jointData.collision,
  31223. spring: options.spring,
  31224. //supporting older version of Oimo
  31225. world: this.world
  31226. };
  31227. switch (impostorJoint.joint.type) {
  31228. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  31229. type = "jointBall";
  31230. break;
  31231. case BABYLON.PhysicsJoint.SpringJoint:
  31232. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  31233. var springData = jointData;
  31234. nativeJointData.min = springData.length || nativeJointData.min;
  31235. //Max should also be set, just make sure it is at least min
  31236. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  31237. case BABYLON.PhysicsJoint.DistanceJoint:
  31238. type = "jointDistance";
  31239. nativeJointData.max = jointData.maxDistance;
  31240. break;
  31241. case BABYLON.PhysicsJoint.PrismaticJoint:
  31242. type = "jointPrisme";
  31243. break;
  31244. case BABYLON.PhysicsJoint.SliderJoint:
  31245. type = "jointSlide";
  31246. break;
  31247. case BABYLON.PhysicsJoint.WheelJoint:
  31248. type = "jointWheel";
  31249. break;
  31250. case BABYLON.PhysicsJoint.HingeJoint:
  31251. default:
  31252. type = "jointHinge";
  31253. break;
  31254. }
  31255. nativeJointData.type = type;
  31256. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  31257. };
  31258. OimoJSPlugin.prototype.removeJoint = function (joint) {
  31259. joint.joint.physicsJoint.dispose();
  31260. };
  31261. OimoJSPlugin.prototype.isSupported = function () {
  31262. return OIMO !== undefined;
  31263. };
  31264. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31265. if (!impostor.physicsBody.sleeping) {
  31266. //TODO check that
  31267. if (impostor.physicsBody.shapes.next) {
  31268. var parentShape = this._getLastShape(impostor.physicsBody);
  31269. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  31270. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  31271. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  31272. }
  31273. else {
  31274. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  31275. }
  31276. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  31277. }
  31278. };
  31279. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31280. var body = impostor.physicsBody;
  31281. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  31282. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  31283. body.syncShapes();
  31284. body.awake();
  31285. };
  31286. OimoJSPlugin.prototype._getLastShape = function (body) {
  31287. var lastShape = body.shapes;
  31288. while (lastShape.next) {
  31289. lastShape = lastShape.next;
  31290. }
  31291. return lastShape;
  31292. };
  31293. OimoJSPlugin.prototype.setVelocity = function (impostor, velocity) {
  31294. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  31295. };
  31296. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  31297. impostor.physicsBody.sleep();
  31298. };
  31299. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  31300. impostor.physicsBody.awake();
  31301. };
  31302. OimoJSPlugin.prototype.dispose = function () {
  31303. this.world.clear();
  31304. };
  31305. return OimoJSPlugin;
  31306. })();
  31307. BABYLON.OimoJSPlugin = OimoJSPlugin;
  31308. })(BABYLON || (BABYLON = {}));
  31309. var BABYLON;
  31310. (function (BABYLON) {
  31311. var DisplayPassPostProcess = (function (_super) {
  31312. __extends(DisplayPassPostProcess, _super);
  31313. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31314. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  31315. }
  31316. return DisplayPassPostProcess;
  31317. })(BABYLON.PostProcess);
  31318. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  31319. })(BABYLON || (BABYLON = {}));
  31320. var BABYLON;
  31321. (function (BABYLON) {
  31322. var SimplificationSettings = (function () {
  31323. function SimplificationSettings(quality, distance, optimizeMesh) {
  31324. this.quality = quality;
  31325. this.distance = distance;
  31326. this.optimizeMesh = optimizeMesh;
  31327. }
  31328. return SimplificationSettings;
  31329. })();
  31330. BABYLON.SimplificationSettings = SimplificationSettings;
  31331. var SimplificationQueue = (function () {
  31332. function SimplificationQueue() {
  31333. this.running = false;
  31334. this._simplificationArray = [];
  31335. }
  31336. SimplificationQueue.prototype.addTask = function (task) {
  31337. this._simplificationArray.push(task);
  31338. };
  31339. SimplificationQueue.prototype.executeNext = function () {
  31340. var task = this._simplificationArray.pop();
  31341. if (task) {
  31342. this.running = true;
  31343. this.runSimplification(task);
  31344. }
  31345. else {
  31346. this.running = false;
  31347. }
  31348. };
  31349. SimplificationQueue.prototype.runSimplification = function (task) {
  31350. var _this = this;
  31351. if (task.parallelProcessing) {
  31352. //parallel simplifier
  31353. task.settings.forEach(function (setting) {
  31354. var simplifier = _this.getSimplifier(task);
  31355. simplifier.simplify(setting, function (newMesh) {
  31356. task.mesh.addLODLevel(setting.distance, newMesh);
  31357. newMesh.isVisible = true;
  31358. //check if it is the last
  31359. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31360. //all done, run the success callback.
  31361. task.successCallback();
  31362. }
  31363. _this.executeNext();
  31364. });
  31365. });
  31366. }
  31367. else {
  31368. //single simplifier.
  31369. var simplifier = this.getSimplifier(task);
  31370. var runDecimation = function (setting, callback) {
  31371. simplifier.simplify(setting, function (newMesh) {
  31372. task.mesh.addLODLevel(setting.distance, newMesh);
  31373. newMesh.isVisible = true;
  31374. //run the next quality level
  31375. callback();
  31376. });
  31377. };
  31378. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31379. runDecimation(task.settings[loop.index], function () {
  31380. loop.executeNext();
  31381. });
  31382. }, function () {
  31383. //execution ended, run the success callback.
  31384. if (task.successCallback) {
  31385. task.successCallback();
  31386. }
  31387. _this.executeNext();
  31388. });
  31389. }
  31390. };
  31391. SimplificationQueue.prototype.getSimplifier = function (task) {
  31392. switch (task.simplificationType) {
  31393. case SimplificationType.QUADRATIC:
  31394. default:
  31395. return new QuadraticErrorSimplification(task.mesh);
  31396. }
  31397. };
  31398. return SimplificationQueue;
  31399. })();
  31400. BABYLON.SimplificationQueue = SimplificationQueue;
  31401. /**
  31402. * The implemented types of simplification.
  31403. * At the moment only Quadratic Error Decimation is implemented.
  31404. */
  31405. (function (SimplificationType) {
  31406. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31407. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31408. var SimplificationType = BABYLON.SimplificationType;
  31409. var DecimationTriangle = (function () {
  31410. function DecimationTriangle(vertices) {
  31411. this.vertices = vertices;
  31412. this.error = new Array(4);
  31413. this.deleted = false;
  31414. this.isDirty = false;
  31415. this.deletePending = false;
  31416. this.borderFactor = 0;
  31417. }
  31418. return DecimationTriangle;
  31419. })();
  31420. BABYLON.DecimationTriangle = DecimationTriangle;
  31421. var DecimationVertex = (function () {
  31422. function DecimationVertex(position, id) {
  31423. this.position = position;
  31424. this.id = id;
  31425. this.isBorder = true;
  31426. this.q = new QuadraticMatrix();
  31427. this.triangleCount = 0;
  31428. this.triangleStart = 0;
  31429. this.originalOffsets = [];
  31430. }
  31431. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31432. this.position.copyFrom(newPosition);
  31433. };
  31434. return DecimationVertex;
  31435. })();
  31436. BABYLON.DecimationVertex = DecimationVertex;
  31437. var QuadraticMatrix = (function () {
  31438. function QuadraticMatrix(data) {
  31439. this.data = new Array(10);
  31440. for (var i = 0; i < 10; ++i) {
  31441. if (data && data[i]) {
  31442. this.data[i] = data[i];
  31443. }
  31444. else {
  31445. this.data[i] = 0;
  31446. }
  31447. }
  31448. }
  31449. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31450. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31451. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31452. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31453. return det;
  31454. };
  31455. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31456. for (var i = 0; i < 10; ++i) {
  31457. this.data[i] += matrix.data[i];
  31458. }
  31459. };
  31460. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31461. for (var i = 0; i < 10; ++i) {
  31462. this.data[i] += data[i];
  31463. }
  31464. };
  31465. QuadraticMatrix.prototype.add = function (matrix) {
  31466. var m = new QuadraticMatrix();
  31467. for (var i = 0; i < 10; ++i) {
  31468. m.data[i] = this.data[i] + matrix.data[i];
  31469. }
  31470. return m;
  31471. };
  31472. QuadraticMatrix.FromData = function (a, b, c, d) {
  31473. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31474. };
  31475. //returning an array to avoid garbage collection
  31476. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31477. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31478. };
  31479. return QuadraticMatrix;
  31480. })();
  31481. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31482. var Reference = (function () {
  31483. function Reference(vertexId, triangleId) {
  31484. this.vertexId = vertexId;
  31485. this.triangleId = triangleId;
  31486. }
  31487. return Reference;
  31488. })();
  31489. BABYLON.Reference = Reference;
  31490. /**
  31491. * An implementation of the Quadratic Error simplification algorithm.
  31492. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31493. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31494. * @author RaananW
  31495. */
  31496. var QuadraticErrorSimplification = (function () {
  31497. function QuadraticErrorSimplification(_mesh) {
  31498. this._mesh = _mesh;
  31499. this.initialized = false;
  31500. this.syncIterations = 5000;
  31501. this.aggressiveness = 7;
  31502. this.decimationIterations = 100;
  31503. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31504. }
  31505. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31506. var _this = this;
  31507. this.initDecimatedMesh();
  31508. //iterating through the submeshes array, one after the other.
  31509. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31510. _this.initWithMesh(loop.index, function () {
  31511. _this.runDecimation(settings, loop.index, function () {
  31512. loop.executeNext();
  31513. });
  31514. }, settings.optimizeMesh);
  31515. }, function () {
  31516. setTimeout(function () {
  31517. successCallback(_this._reconstructedMesh);
  31518. }, 0);
  31519. });
  31520. };
  31521. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31522. var _this = this;
  31523. var gCount = 0;
  31524. triangle.vertices.forEach(function (vertex) {
  31525. var count = 0;
  31526. var vPos = vertex.position;
  31527. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31528. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31529. ++count;
  31530. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  31531. ++count;
  31532. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  31533. ++count;
  31534. if (count > 1) {
  31535. ++gCount;
  31536. }
  31537. ;
  31538. });
  31539. if (gCount > 1) {
  31540. console.log(triangle, gCount);
  31541. }
  31542. return gCount > 1;
  31543. };
  31544. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31545. var _this = this;
  31546. var targetCount = ~~(this.triangles.length * settings.quality);
  31547. var deletedTriangles = 0;
  31548. var triangleCount = this.triangles.length;
  31549. var iterationFunction = function (iteration, callback) {
  31550. setTimeout(function () {
  31551. if (iteration % 5 === 0) {
  31552. _this.updateMesh(iteration === 0);
  31553. }
  31554. for (var i = 0; i < _this.triangles.length; ++i) {
  31555. _this.triangles[i].isDirty = false;
  31556. }
  31557. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31558. var trianglesIterator = function (i) {
  31559. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31560. var t = _this.triangles[tIdx];
  31561. if (!t)
  31562. return;
  31563. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31564. return;
  31565. }
  31566. for (var j = 0; j < 3; ++j) {
  31567. if (t.error[j] < threshold) {
  31568. var deleted0 = [];
  31569. var deleted1 = [];
  31570. var v0 = t.vertices[j];
  31571. var v1 = t.vertices[(j + 1) % 3];
  31572. if (v0.isBorder !== v1.isBorder)
  31573. continue;
  31574. var p = BABYLON.Vector3.Zero();
  31575. var n = BABYLON.Vector3.Zero();
  31576. var uv = BABYLON.Vector2.Zero();
  31577. var color = new BABYLON.Color4(0, 0, 0, 1);
  31578. _this.calculateError(v0, v1, p, n, uv, color);
  31579. var delTr = [];
  31580. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31581. continue;
  31582. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31583. continue;
  31584. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31585. continue;
  31586. var uniqueArray = [];
  31587. delTr.forEach(function (deletedT) {
  31588. if (uniqueArray.indexOf(deletedT) === -1) {
  31589. deletedT.deletePending = true;
  31590. uniqueArray.push(deletedT);
  31591. }
  31592. });
  31593. if (uniqueArray.length % 2 !== 0) {
  31594. continue;
  31595. }
  31596. v0.q = v1.q.add(v0.q);
  31597. v0.updatePosition(p);
  31598. var tStart = _this.references.length;
  31599. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31600. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31601. var tCount = _this.references.length - tStart;
  31602. if (tCount <= v0.triangleCount) {
  31603. if (tCount) {
  31604. for (var c = 0; c < tCount; c++) {
  31605. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31606. }
  31607. }
  31608. }
  31609. else {
  31610. v0.triangleStart = tStart;
  31611. }
  31612. v0.triangleCount = tCount;
  31613. break;
  31614. }
  31615. }
  31616. };
  31617. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31618. }, 0);
  31619. };
  31620. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31621. if (triangleCount - deletedTriangles <= targetCount)
  31622. loop.breakLoop();
  31623. else {
  31624. iterationFunction(loop.index, function () {
  31625. loop.executeNext();
  31626. });
  31627. }
  31628. }, function () {
  31629. setTimeout(function () {
  31630. //reconstruct this part of the mesh
  31631. _this.reconstructMesh(submeshIndex);
  31632. successCallback();
  31633. }, 0);
  31634. });
  31635. };
  31636. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31637. var _this = this;
  31638. this.vertices = [];
  31639. this.triangles = [];
  31640. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31641. var indices = this._mesh.getIndices();
  31642. var submesh = this._mesh.subMeshes[submeshIndex];
  31643. var findInVertices = function (positionToSearch) {
  31644. if (optimizeMesh) {
  31645. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31646. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31647. return _this.vertices[ii];
  31648. }
  31649. }
  31650. }
  31651. return null;
  31652. };
  31653. var vertexReferences = [];
  31654. var vertexInit = function (i) {
  31655. var offset = i + submesh.verticesStart;
  31656. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31657. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31658. vertex.originalOffsets.push(offset);
  31659. if (vertex.id === _this.vertices.length) {
  31660. _this.vertices.push(vertex);
  31661. }
  31662. vertexReferences.push(vertex.id);
  31663. };
  31664. //var totalVertices = mesh.getTotalVertices();
  31665. var totalVertices = submesh.verticesCount;
  31666. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31667. var indicesInit = function (i) {
  31668. var offset = (submesh.indexStart / 3) + i;
  31669. var pos = (offset * 3);
  31670. var i0 = indices[pos + 0];
  31671. var i1 = indices[pos + 1];
  31672. var i2 = indices[pos + 2];
  31673. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31674. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31675. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31676. var triangle = new DecimationTriangle([v0, v1, v2]);
  31677. triangle.originalOffset = pos;
  31678. _this.triangles.push(triangle);
  31679. };
  31680. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31681. _this.init(callback);
  31682. });
  31683. });
  31684. };
  31685. QuadraticErrorSimplification.prototype.init = function (callback) {
  31686. var _this = this;
  31687. var triangleInit1 = function (i) {
  31688. var t = _this.triangles[i];
  31689. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31690. for (var j = 0; j < 3; j++) {
  31691. 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))));
  31692. }
  31693. };
  31694. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31695. var triangleInit2 = function (i) {
  31696. var t = _this.triangles[i];
  31697. for (var j = 0; j < 3; ++j) {
  31698. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31699. }
  31700. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31701. };
  31702. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31703. _this.initialized = true;
  31704. callback();
  31705. });
  31706. });
  31707. };
  31708. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31709. var newTriangles = [];
  31710. var i;
  31711. for (i = 0; i < this.vertices.length; ++i) {
  31712. this.vertices[i].triangleCount = 0;
  31713. }
  31714. var t;
  31715. var j;
  31716. for (i = 0; i < this.triangles.length; ++i) {
  31717. if (!this.triangles[i].deleted) {
  31718. t = this.triangles[i];
  31719. for (j = 0; j < 3; ++j) {
  31720. t.vertices[j].triangleCount = 1;
  31721. }
  31722. newTriangles.push(t);
  31723. }
  31724. }
  31725. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  31726. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  31727. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  31728. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  31729. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31730. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31731. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31732. var vertexCount = 0;
  31733. for (i = 0; i < this.vertices.length; ++i) {
  31734. var vertex = this.vertices[i];
  31735. vertex.id = vertexCount;
  31736. if (vertex.triangleCount) {
  31737. vertex.originalOffsets.forEach(function (originalOffset) {
  31738. newPositionData.push(vertex.position.x);
  31739. newPositionData.push(vertex.position.y);
  31740. newPositionData.push(vertex.position.z);
  31741. newNormalData.push(normalData[originalOffset * 3]);
  31742. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31743. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31744. if (uvs && uvs.length) {
  31745. newUVsData.push(uvs[(originalOffset * 2)]);
  31746. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31747. }
  31748. else if (colorsData && colorsData.length) {
  31749. newColorsData.push(colorsData[(originalOffset * 4)]);
  31750. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31751. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31752. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31753. }
  31754. ++vertexCount;
  31755. });
  31756. }
  31757. }
  31758. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31759. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31760. var submeshesArray = this._reconstructedMesh.subMeshes;
  31761. this._reconstructedMesh.subMeshes = [];
  31762. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31763. var originalIndices = this._mesh.getIndices();
  31764. for (i = 0; i < newTriangles.length; ++i) {
  31765. t = newTriangles[i]; //now get the new referencing point for each vertex
  31766. [0, 1, 2].forEach(function (idx) {
  31767. var id = originalIndices[t.originalOffset + idx];
  31768. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31769. if (offset < 0)
  31770. offset = 0;
  31771. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31772. });
  31773. }
  31774. //overwriting the old vertex buffers and indices.
  31775. this._reconstructedMesh.setIndices(newIndicesArray);
  31776. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31777. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31778. if (newUVsData.length > 0)
  31779. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31780. if (newColorsData.length > 0)
  31781. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31782. //create submesh
  31783. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31784. if (submeshIndex > 0) {
  31785. this._reconstructedMesh.subMeshes = [];
  31786. submeshesArray.forEach(function (submesh) {
  31787. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31788. });
  31789. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31790. }
  31791. };
  31792. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31793. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31794. this._reconstructedMesh.material = this._mesh.material;
  31795. this._reconstructedMesh.parent = this._mesh.parent;
  31796. this._reconstructedMesh.isVisible = false;
  31797. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31798. };
  31799. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31800. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31801. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31802. if (t.deleted)
  31803. continue;
  31804. var s = this.references[vertex1.triangleStart + i].vertexId;
  31805. var v1 = t.vertices[(s + 1) % 3];
  31806. var v2 = t.vertices[(s + 2) % 3];
  31807. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31808. deletedArray[i] = true;
  31809. delTr.push(t);
  31810. continue;
  31811. }
  31812. var d1 = v1.position.subtract(point);
  31813. d1 = d1.normalize();
  31814. var d2 = v2.position.subtract(point);
  31815. d2 = d2.normalize();
  31816. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31817. return true;
  31818. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31819. deletedArray[i] = false;
  31820. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31821. return true;
  31822. }
  31823. return false;
  31824. };
  31825. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31826. var newDeleted = deletedTriangles;
  31827. for (var i = 0; i < vertex.triangleCount; ++i) {
  31828. var ref = this.references[vertex.triangleStart + i];
  31829. var t = this.triangles[ref.triangleId];
  31830. if (t.deleted)
  31831. continue;
  31832. if (deletedArray[i] && t.deletePending) {
  31833. t.deleted = true;
  31834. newDeleted++;
  31835. continue;
  31836. }
  31837. t.vertices[ref.vertexId] = origVertex;
  31838. t.isDirty = true;
  31839. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31840. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31841. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31842. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31843. this.references.push(ref);
  31844. }
  31845. return newDeleted;
  31846. };
  31847. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31848. for (var i = 0; i < this.vertices.length; ++i) {
  31849. var vCount = [];
  31850. var vId = [];
  31851. var v = this.vertices[i];
  31852. var j;
  31853. for (j = 0; j < v.triangleCount; ++j) {
  31854. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31855. for (var ii = 0; ii < 3; ii++) {
  31856. var ofs = 0;
  31857. var vv = triangle.vertices[ii];
  31858. while (ofs < vCount.length) {
  31859. if (vId[ofs] === vv.id)
  31860. break;
  31861. ++ofs;
  31862. }
  31863. if (ofs === vCount.length) {
  31864. vCount.push(1);
  31865. vId.push(vv.id);
  31866. }
  31867. else {
  31868. vCount[ofs]++;
  31869. }
  31870. }
  31871. }
  31872. for (j = 0; j < vCount.length; ++j) {
  31873. if (vCount[j] === 1) {
  31874. this.vertices[vId[j]].isBorder = true;
  31875. }
  31876. else {
  31877. this.vertices[vId[j]].isBorder = false;
  31878. }
  31879. }
  31880. }
  31881. };
  31882. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31883. if (identifyBorders === void 0) { identifyBorders = false; }
  31884. var i;
  31885. if (!identifyBorders) {
  31886. var newTrianglesVector = [];
  31887. for (i = 0; i < this.triangles.length; ++i) {
  31888. if (!this.triangles[i].deleted) {
  31889. newTrianglesVector.push(this.triangles[i]);
  31890. }
  31891. }
  31892. this.triangles = newTrianglesVector;
  31893. }
  31894. for (i = 0; i < this.vertices.length; ++i) {
  31895. this.vertices[i].triangleCount = 0;
  31896. this.vertices[i].triangleStart = 0;
  31897. }
  31898. var t;
  31899. var j;
  31900. var v;
  31901. for (i = 0; i < this.triangles.length; ++i) {
  31902. t = this.triangles[i];
  31903. for (j = 0; j < 3; ++j) {
  31904. v = t.vertices[j];
  31905. v.triangleCount++;
  31906. }
  31907. }
  31908. var tStart = 0;
  31909. for (i = 0; i < this.vertices.length; ++i) {
  31910. this.vertices[i].triangleStart = tStart;
  31911. tStart += this.vertices[i].triangleCount;
  31912. this.vertices[i].triangleCount = 0;
  31913. }
  31914. var newReferences = new Array(this.triangles.length * 3);
  31915. for (i = 0; i < this.triangles.length; ++i) {
  31916. t = this.triangles[i];
  31917. for (j = 0; j < 3; ++j) {
  31918. v = t.vertices[j];
  31919. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31920. v.triangleCount++;
  31921. }
  31922. }
  31923. this.references = newReferences;
  31924. if (identifyBorders) {
  31925. this.identifyBorder();
  31926. }
  31927. };
  31928. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31929. var x = point.x;
  31930. var y = point.y;
  31931. var z = point.z;
  31932. 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
  31933. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31934. };
  31935. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31936. var q = vertex1.q.add(vertex2.q);
  31937. var border = vertex1.isBorder && vertex2.isBorder;
  31938. var error = 0;
  31939. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31940. if (qDet !== 0 && !border) {
  31941. if (!pointResult) {
  31942. pointResult = BABYLON.Vector3.Zero();
  31943. }
  31944. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31945. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31946. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31947. error = this.vertexError(q, pointResult);
  31948. }
  31949. else {
  31950. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31951. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31952. var error1 = this.vertexError(q, vertex1.position);
  31953. var error2 = this.vertexError(q, vertex2.position);
  31954. var error3 = this.vertexError(q, p3);
  31955. error = Math.min(error1, error2, error3);
  31956. if (error === error1) {
  31957. if (pointResult) {
  31958. pointResult.copyFrom(vertex1.position);
  31959. }
  31960. }
  31961. else if (error === error2) {
  31962. if (pointResult) {
  31963. pointResult.copyFrom(vertex2.position);
  31964. }
  31965. }
  31966. else {
  31967. if (pointResult) {
  31968. pointResult.copyFrom(p3);
  31969. }
  31970. }
  31971. }
  31972. return error;
  31973. };
  31974. return QuadraticErrorSimplification;
  31975. })();
  31976. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31977. })(BABYLON || (BABYLON = {}));
  31978. var BABYLON;
  31979. (function (BABYLON) {
  31980. var serializedGeometries = [];
  31981. var serializeGeometry = function (geometry, serializationGeometries) {
  31982. if (serializedGeometries[geometry.id]) {
  31983. return;
  31984. }
  31985. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  31986. serializationGeometries.boxes.push(geometry.serialize());
  31987. }
  31988. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  31989. serializationGeometries.spheres.push(geometry.serialize());
  31990. }
  31991. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  31992. serializationGeometries.cylinders.push(geometry.serialize());
  31993. }
  31994. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  31995. serializationGeometries.toruses.push(geometry.serialize());
  31996. }
  31997. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  31998. serializationGeometries.grounds.push(geometry.serialize());
  31999. }
  32000. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  32001. serializationGeometries.planes.push(geometry.serialize());
  32002. }
  32003. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  32004. serializationGeometries.torusKnots.push(geometry.serialize());
  32005. }
  32006. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  32007. throw new Error("Unknown primitive type");
  32008. }
  32009. else {
  32010. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  32011. }
  32012. serializedGeometries[geometry.id] = true;
  32013. };
  32014. var serializeMesh = function (mesh, serializationScene) {
  32015. var serializationObject = {};
  32016. serializationObject.name = mesh.name;
  32017. serializationObject.id = mesh.id;
  32018. if (BABYLON.Tags.HasTags(mesh)) {
  32019. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  32020. }
  32021. serializationObject.position = mesh.position.asArray();
  32022. if (mesh.rotationQuaternion) {
  32023. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  32024. }
  32025. else if (mesh.rotation) {
  32026. serializationObject.rotation = mesh.rotation.asArray();
  32027. }
  32028. serializationObject.scaling = mesh.scaling.asArray();
  32029. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  32030. serializationObject.isEnabled = mesh.isEnabled();
  32031. serializationObject.isVisible = mesh.isVisible;
  32032. serializationObject.infiniteDistance = mesh.infiniteDistance;
  32033. serializationObject.pickable = mesh.isPickable;
  32034. serializationObject.receiveShadows = mesh.receiveShadows;
  32035. serializationObject.billboardMode = mesh.billboardMode;
  32036. serializationObject.visibility = mesh.visibility;
  32037. serializationObject.checkCollisions = mesh.checkCollisions;
  32038. // Parent
  32039. if (mesh.parent) {
  32040. serializationObject.parentId = mesh.parent.id;
  32041. }
  32042. // Geometry
  32043. var geometry = mesh._geometry;
  32044. if (geometry) {
  32045. var geometryId = geometry.id;
  32046. serializationObject.geometryId = geometryId;
  32047. if (!mesh.getScene().getGeometryByID(geometryId)) {
  32048. // 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
  32049. serializeGeometry(geometry, serializationScene.geometries);
  32050. }
  32051. // SubMeshes
  32052. serializationObject.subMeshes = [];
  32053. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32054. var subMesh = mesh.subMeshes[subIndex];
  32055. serializationObject.subMeshes.push({
  32056. materialIndex: subMesh.materialIndex,
  32057. verticesStart: subMesh.verticesStart,
  32058. verticesCount: subMesh.verticesCount,
  32059. indexStart: subMesh.indexStart,
  32060. indexCount: subMesh.indexCount
  32061. });
  32062. }
  32063. }
  32064. // Material
  32065. if (mesh.material) {
  32066. serializationObject.materialId = mesh.material.id;
  32067. }
  32068. else {
  32069. mesh.material = null;
  32070. }
  32071. // Skeleton
  32072. if (mesh.skeleton) {
  32073. serializationObject.skeletonId = mesh.skeleton.id;
  32074. }
  32075. // Physics
  32076. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  32077. serializationObject.physicsMass = mesh.getPhysicsMass();
  32078. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  32079. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  32080. switch (mesh.getPhysicsImpostor().type) {
  32081. case BABYLON.PhysicsEngine.BoxImpostor:
  32082. serializationObject.physicsImpostor = 1;
  32083. break;
  32084. case BABYLON.PhysicsEngine.SphereImpostor:
  32085. serializationObject.physicsImpostor = 2;
  32086. break;
  32087. }
  32088. }
  32089. // Instances
  32090. serializationObject.instances = [];
  32091. for (var index = 0; index < mesh.instances.length; index++) {
  32092. var instance = mesh.instances[index];
  32093. var serializationInstance = {
  32094. name: instance.name,
  32095. position: instance.position.asArray(),
  32096. scaling: instance.scaling.asArray()
  32097. };
  32098. if (instance.rotationQuaternion) {
  32099. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32100. }
  32101. else if (instance.rotation) {
  32102. serializationInstance.rotation = instance.rotation.asArray();
  32103. }
  32104. serializationObject.instances.push(serializationInstance);
  32105. // Animations
  32106. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32107. serializationInstance.ranges = instance.serializeAnimationRanges();
  32108. }
  32109. // Animations
  32110. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  32111. serializationObject.ranges = mesh.serializeAnimationRanges();
  32112. // Layer mask
  32113. serializationObject.layerMask = mesh.layerMask;
  32114. return serializationObject;
  32115. };
  32116. var finalizeSingleMesh = function (mesh, serializationObject) {
  32117. //only works if the mesh is already loaded
  32118. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32119. //serialize material
  32120. if (mesh.material) {
  32121. if (mesh.material instanceof BABYLON.StandardMaterial) {
  32122. serializationObject.materials = serializationObject.materials || [];
  32123. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32124. serializationObject.materials.push(mesh.material.serialize());
  32125. }
  32126. }
  32127. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  32128. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  32129. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32130. serializationObject.multiMaterials.push(mesh.material.serialize());
  32131. }
  32132. }
  32133. }
  32134. //serialize geometry
  32135. var geometry = mesh._geometry;
  32136. if (geometry) {
  32137. if (!serializationObject.geometries) {
  32138. serializationObject.geometries = {};
  32139. serializationObject.geometries.boxes = [];
  32140. serializationObject.geometries.spheres = [];
  32141. serializationObject.geometries.cylinders = [];
  32142. serializationObject.geometries.toruses = [];
  32143. serializationObject.geometries.grounds = [];
  32144. serializationObject.geometries.planes = [];
  32145. serializationObject.geometries.torusKnots = [];
  32146. serializationObject.geometries.vertexData = [];
  32147. }
  32148. serializeGeometry(geometry, serializationObject.geometries);
  32149. }
  32150. // Skeletons
  32151. if (mesh.skeleton) {
  32152. serializationObject.skeletons = serializationObject.skeletons || [];
  32153. serializationObject.skeletons.push(mesh.skeleton.serialize());
  32154. }
  32155. //serialize the actual mesh
  32156. serializationObject.meshes = serializationObject.meshes || [];
  32157. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32158. }
  32159. };
  32160. var SceneSerializer = (function () {
  32161. function SceneSerializer() {
  32162. }
  32163. SceneSerializer.ClearCache = function () {
  32164. serializedGeometries = [];
  32165. };
  32166. SceneSerializer.Serialize = function (scene) {
  32167. var serializationObject = {};
  32168. // Scene
  32169. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  32170. serializationObject.autoClear = scene.autoClear;
  32171. serializationObject.clearColor = scene.clearColor.asArray();
  32172. serializationObject.ambientColor = scene.ambientColor.asArray();
  32173. serializationObject.gravity = scene.gravity.asArray();
  32174. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  32175. serializationObject.workerCollisions = scene.workerCollisions;
  32176. // Fog
  32177. if (scene.fogMode && scene.fogMode !== 0) {
  32178. serializationObject.fogMode = scene.fogMode;
  32179. serializationObject.fogColor = scene.fogColor.asArray();
  32180. serializationObject.fogStart = scene.fogStart;
  32181. serializationObject.fogEnd = scene.fogEnd;
  32182. serializationObject.fogDensity = scene.fogDensity;
  32183. }
  32184. //Physics
  32185. if (scene.isPhysicsEnabled()) {
  32186. serializationObject.physicsEnabled = true;
  32187. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  32188. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  32189. }
  32190. // Lights
  32191. serializationObject.lights = [];
  32192. var index;
  32193. var light;
  32194. for (index = 0; index < scene.lights.length; index++) {
  32195. light = scene.lights[index];
  32196. serializationObject.lights.push(light.serialize());
  32197. }
  32198. // Cameras
  32199. serializationObject.cameras = [];
  32200. for (index = 0; index < scene.cameras.length; index++) {
  32201. var camera = scene.cameras[index];
  32202. serializationObject.cameras.push(camera.serialize());
  32203. }
  32204. if (scene.activeCamera) {
  32205. serializationObject.activeCameraID = scene.activeCamera.id;
  32206. }
  32207. // Animations
  32208. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  32209. // Materials
  32210. serializationObject.materials = [];
  32211. serializationObject.multiMaterials = [];
  32212. var material;
  32213. for (index = 0; index < scene.materials.length; index++) {
  32214. material = scene.materials[index];
  32215. serializationObject.materials.push(material.serialize());
  32216. }
  32217. // MultiMaterials
  32218. serializationObject.multiMaterials = [];
  32219. for (index = 0; index < scene.multiMaterials.length; index++) {
  32220. var multiMaterial = scene.multiMaterials[index];
  32221. serializationObject.multiMaterials.push(multiMaterial.serialize());
  32222. }
  32223. // Skeletons
  32224. serializationObject.skeletons = [];
  32225. for (index = 0; index < scene.skeletons.length; index++) {
  32226. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  32227. }
  32228. // Geometries
  32229. serializationObject.geometries = {};
  32230. serializationObject.geometries.boxes = [];
  32231. serializationObject.geometries.spheres = [];
  32232. serializationObject.geometries.cylinders = [];
  32233. serializationObject.geometries.toruses = [];
  32234. serializationObject.geometries.grounds = [];
  32235. serializationObject.geometries.planes = [];
  32236. serializationObject.geometries.torusKnots = [];
  32237. serializationObject.geometries.vertexData = [];
  32238. serializedGeometries = [];
  32239. var geometries = scene.getGeometries();
  32240. for (index = 0; index < geometries.length; index++) {
  32241. var geometry = geometries[index];
  32242. if (geometry.isReady()) {
  32243. serializeGeometry(geometry, serializationObject.geometries);
  32244. }
  32245. }
  32246. // Meshes
  32247. serializationObject.meshes = [];
  32248. for (index = 0; index < scene.meshes.length; index++) {
  32249. var abstractMesh = scene.meshes[index];
  32250. if (abstractMesh instanceof BABYLON.Mesh) {
  32251. var mesh = abstractMesh;
  32252. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32253. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32254. }
  32255. }
  32256. }
  32257. // Particles Systems
  32258. serializationObject.particleSystems = [];
  32259. for (index = 0; index < scene.particleSystems.length; index++) {
  32260. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  32261. }
  32262. // Lens flares
  32263. serializationObject.lensFlareSystems = [];
  32264. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  32265. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  32266. }
  32267. // Shadows
  32268. serializationObject.shadowGenerators = [];
  32269. for (index = 0; index < scene.lights.length; index++) {
  32270. light = scene.lights[index];
  32271. if (light.getShadowGenerator()) {
  32272. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  32273. }
  32274. }
  32275. return serializationObject;
  32276. };
  32277. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  32278. if (withParents === void 0) { withParents = false; }
  32279. if (withChildren === void 0) { withChildren = false; }
  32280. var serializationObject = {};
  32281. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  32282. if (withParents || withChildren) {
  32283. //deliberate for loop! not for each, appended should be processed as well.
  32284. for (var i = 0; i < toSerialize.length; ++i) {
  32285. if (withChildren) {
  32286. toSerialize[i].getDescendants().forEach(function (node) {
  32287. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  32288. toSerialize.push(node);
  32289. }
  32290. });
  32291. }
  32292. //make sure the array doesn't contain the object already
  32293. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  32294. toSerialize.push(toSerialize[i].parent);
  32295. }
  32296. }
  32297. }
  32298. toSerialize.forEach(function (mesh) {
  32299. finalizeSingleMesh(mesh, serializationObject);
  32300. });
  32301. return serializationObject;
  32302. };
  32303. return SceneSerializer;
  32304. })();
  32305. BABYLON.SceneSerializer = SceneSerializer;
  32306. })(BABYLON || (BABYLON = {}));
  32307. var BABYLON;
  32308. (function (BABYLON) {
  32309. // Unique ID when we import meshes from Babylon to CSG
  32310. var currentCSGMeshId = 0;
  32311. // # class Vertex
  32312. // Represents a vertex of a polygon. Use your own vertex class instead of this
  32313. // one to provide additional features like texture coordinates and vertex
  32314. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  32315. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  32316. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  32317. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  32318. // is not used anywhere else.
  32319. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  32320. var Vertex = (function () {
  32321. function Vertex(pos, normal, uv) {
  32322. this.pos = pos;
  32323. this.normal = normal;
  32324. this.uv = uv;
  32325. }
  32326. Vertex.prototype.clone = function () {
  32327. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  32328. };
  32329. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  32330. // orientation of a polygon is flipped.
  32331. Vertex.prototype.flip = function () {
  32332. this.normal = this.normal.scale(-1);
  32333. };
  32334. // Create a new vertex between this vertex and `other` by linearly
  32335. // interpolating all properties using a parameter of `t`. Subclasses should
  32336. // override this to interpolate additional properties.
  32337. Vertex.prototype.interpolate = function (other, t) {
  32338. 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));
  32339. };
  32340. return Vertex;
  32341. })();
  32342. // # class Plane
  32343. // Represents a plane in 3D space.
  32344. var Plane = (function () {
  32345. function Plane(normal, w) {
  32346. this.normal = normal;
  32347. this.w = w;
  32348. }
  32349. Plane.FromPoints = function (a, b, c) {
  32350. var v0 = c.subtract(a);
  32351. var v1 = b.subtract(a);
  32352. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  32353. return null;
  32354. }
  32355. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  32356. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  32357. };
  32358. Plane.prototype.clone = function () {
  32359. return new Plane(this.normal.clone(), this.w);
  32360. };
  32361. Plane.prototype.flip = function () {
  32362. this.normal.scaleInPlace(-1);
  32363. this.w = -this.w;
  32364. };
  32365. // Split `polygon` by this plane if needed, then put the polygon or polygon
  32366. // fragments in the appropriate lists. Coplanar polygons go into either
  32367. // `coplanarFront` or `coplanarBack` depending on their orientation with
  32368. // respect to this plane. Polygons in front or in back of this plane go into
  32369. // either `front` or `back`.
  32370. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  32371. var COPLANAR = 0;
  32372. var FRONT = 1;
  32373. var BACK = 2;
  32374. var SPANNING = 3;
  32375. // Classify each point as well as the entire polygon into one of the above
  32376. // four classes.
  32377. var polygonType = 0;
  32378. var types = [];
  32379. var i;
  32380. var t;
  32381. for (i = 0; i < polygon.vertices.length; i++) {
  32382. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  32383. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  32384. polygonType |= type;
  32385. types.push(type);
  32386. }
  32387. // Put the polygon in the correct list, splitting it when necessary.
  32388. switch (polygonType) {
  32389. case COPLANAR:
  32390. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  32391. break;
  32392. case FRONT:
  32393. front.push(polygon);
  32394. break;
  32395. case BACK:
  32396. back.push(polygon);
  32397. break;
  32398. case SPANNING:
  32399. var f = [], b = [];
  32400. for (i = 0; i < polygon.vertices.length; i++) {
  32401. var j = (i + 1) % polygon.vertices.length;
  32402. var ti = types[i], tj = types[j];
  32403. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  32404. if (ti !== BACK)
  32405. f.push(vi);
  32406. if (ti !== FRONT)
  32407. b.push(ti !== BACK ? vi.clone() : vi);
  32408. if ((ti | tj) === SPANNING) {
  32409. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  32410. var v = vi.interpolate(vj, t);
  32411. f.push(v);
  32412. b.push(v.clone());
  32413. }
  32414. }
  32415. var poly;
  32416. if (f.length >= 3) {
  32417. poly = new Polygon(f, polygon.shared);
  32418. if (poly.plane)
  32419. front.push(poly);
  32420. }
  32421. if (b.length >= 3) {
  32422. poly = new Polygon(b, polygon.shared);
  32423. if (poly.plane)
  32424. back.push(poly);
  32425. }
  32426. break;
  32427. }
  32428. };
  32429. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  32430. // point is on the plane.
  32431. Plane.EPSILON = 1e-5;
  32432. return Plane;
  32433. })();
  32434. // # class Polygon
  32435. // Represents a convex polygon. The vertices used to initialize a polygon must
  32436. // be coplanar and form a convex loop.
  32437. //
  32438. // Each convex polygon has a `shared` property, which is shared between all
  32439. // polygons that are clones of each other or were split from the same polygon.
  32440. // This can be used to define per-polygon properties (such as surface color).
  32441. var Polygon = (function () {
  32442. function Polygon(vertices, shared) {
  32443. this.vertices = vertices;
  32444. this.shared = shared;
  32445. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  32446. }
  32447. Polygon.prototype.clone = function () {
  32448. var vertices = this.vertices.map(function (v) { return v.clone(); });
  32449. return new Polygon(vertices, this.shared);
  32450. };
  32451. Polygon.prototype.flip = function () {
  32452. this.vertices.reverse().map(function (v) { v.flip(); });
  32453. this.plane.flip();
  32454. };
  32455. return Polygon;
  32456. })();
  32457. // # class Node
  32458. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  32459. // by picking a polygon to split along. That polygon (and all other coplanar
  32460. // polygons) are added directly to that node and the other polygons are added to
  32461. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  32462. // no distinction between internal and leaf nodes.
  32463. var Node = (function () {
  32464. function Node(polygons) {
  32465. this.plane = null;
  32466. this.front = null;
  32467. this.back = null;
  32468. this.polygons = [];
  32469. if (polygons) {
  32470. this.build(polygons);
  32471. }
  32472. }
  32473. Node.prototype.clone = function () {
  32474. var node = new Node();
  32475. node.plane = this.plane && this.plane.clone();
  32476. node.front = this.front && this.front.clone();
  32477. node.back = this.back && this.back.clone();
  32478. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  32479. return node;
  32480. };
  32481. // Convert solid space to empty space and empty space to solid space.
  32482. Node.prototype.invert = function () {
  32483. for (var i = 0; i < this.polygons.length; i++) {
  32484. this.polygons[i].flip();
  32485. }
  32486. if (this.plane) {
  32487. this.plane.flip();
  32488. }
  32489. if (this.front) {
  32490. this.front.invert();
  32491. }
  32492. if (this.back) {
  32493. this.back.invert();
  32494. }
  32495. var temp = this.front;
  32496. this.front = this.back;
  32497. this.back = temp;
  32498. };
  32499. // Recursively remove all polygons in `polygons` that are inside this BSP
  32500. // tree.
  32501. Node.prototype.clipPolygons = function (polygons) {
  32502. if (!this.plane)
  32503. return polygons.slice();
  32504. var front = [], back = [];
  32505. for (var i = 0; i < polygons.length; i++) {
  32506. this.plane.splitPolygon(polygons[i], front, back, front, back);
  32507. }
  32508. if (this.front) {
  32509. front = this.front.clipPolygons(front);
  32510. }
  32511. if (this.back) {
  32512. back = this.back.clipPolygons(back);
  32513. }
  32514. else {
  32515. back = [];
  32516. }
  32517. return front.concat(back);
  32518. };
  32519. // Remove all polygons in this BSP tree that are inside the other BSP tree
  32520. // `bsp`.
  32521. Node.prototype.clipTo = function (bsp) {
  32522. this.polygons = bsp.clipPolygons(this.polygons);
  32523. if (this.front)
  32524. this.front.clipTo(bsp);
  32525. if (this.back)
  32526. this.back.clipTo(bsp);
  32527. };
  32528. // Return a list of all polygons in this BSP tree.
  32529. Node.prototype.allPolygons = function () {
  32530. var polygons = this.polygons.slice();
  32531. if (this.front)
  32532. polygons = polygons.concat(this.front.allPolygons());
  32533. if (this.back)
  32534. polygons = polygons.concat(this.back.allPolygons());
  32535. return polygons;
  32536. };
  32537. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  32538. // new polygons are filtered down to the bottom of the tree and become new
  32539. // nodes there. Each set of polygons is partitioned using the first polygon
  32540. // (no heuristic is used to pick a good split).
  32541. Node.prototype.build = function (polygons) {
  32542. if (!polygons.length)
  32543. return;
  32544. if (!this.plane)
  32545. this.plane = polygons[0].plane.clone();
  32546. var front = [], back = [];
  32547. for (var i = 0; i < polygons.length; i++) {
  32548. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  32549. }
  32550. if (front.length) {
  32551. if (!this.front)
  32552. this.front = new Node();
  32553. this.front.build(front);
  32554. }
  32555. if (back.length) {
  32556. if (!this.back)
  32557. this.back = new Node();
  32558. this.back.build(back);
  32559. }
  32560. };
  32561. return Node;
  32562. })();
  32563. var CSG = (function () {
  32564. function CSG() {
  32565. this.polygons = new Array();
  32566. }
  32567. // Convert BABYLON.Mesh to BABYLON.CSG
  32568. CSG.FromMesh = function (mesh) {
  32569. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  32570. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  32571. if (mesh instanceof BABYLON.Mesh) {
  32572. mesh.computeWorldMatrix(true);
  32573. matrix = mesh.getWorldMatrix();
  32574. meshPosition = mesh.position.clone();
  32575. meshRotation = mesh.rotation.clone();
  32576. if (mesh.rotationQuaternion) {
  32577. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  32578. }
  32579. meshScaling = mesh.scaling.clone();
  32580. }
  32581. else {
  32582. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  32583. }
  32584. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32585. var subMeshes = mesh.subMeshes;
  32586. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  32587. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  32588. vertices = [];
  32589. for (var j = 0; j < 3; j++) {
  32590. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  32591. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  32592. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  32593. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  32594. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  32595. vertex = new Vertex(position, normal, uv);
  32596. vertices.push(vertex);
  32597. }
  32598. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  32599. // To handle the case of degenerated triangle
  32600. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  32601. if (polygon.plane)
  32602. polygons.push(polygon);
  32603. }
  32604. }
  32605. var csg = CSG.FromPolygons(polygons);
  32606. csg.matrix = matrix;
  32607. csg.position = meshPosition;
  32608. csg.rotation = meshRotation;
  32609. csg.scaling = meshScaling;
  32610. csg.rotationQuaternion = meshRotationQuaternion;
  32611. currentCSGMeshId++;
  32612. return csg;
  32613. };
  32614. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  32615. CSG.FromPolygons = function (polygons) {
  32616. var csg = new CSG();
  32617. csg.polygons = polygons;
  32618. return csg;
  32619. };
  32620. CSG.prototype.clone = function () {
  32621. var csg = new CSG();
  32622. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  32623. csg.copyTransformAttributes(this);
  32624. return csg;
  32625. };
  32626. CSG.prototype.toPolygons = function () {
  32627. return this.polygons;
  32628. };
  32629. CSG.prototype.union = function (csg) {
  32630. var a = new Node(this.clone().polygons);
  32631. var b = new Node(csg.clone().polygons);
  32632. a.clipTo(b);
  32633. b.clipTo(a);
  32634. b.invert();
  32635. b.clipTo(a);
  32636. b.invert();
  32637. a.build(b.allPolygons());
  32638. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32639. };
  32640. CSG.prototype.unionInPlace = function (csg) {
  32641. var a = new Node(this.polygons);
  32642. var b = new Node(csg.polygons);
  32643. a.clipTo(b);
  32644. b.clipTo(a);
  32645. b.invert();
  32646. b.clipTo(a);
  32647. b.invert();
  32648. a.build(b.allPolygons());
  32649. this.polygons = a.allPolygons();
  32650. };
  32651. CSG.prototype.subtract = function (csg) {
  32652. var a = new Node(this.clone().polygons);
  32653. var b = new Node(csg.clone().polygons);
  32654. a.invert();
  32655. a.clipTo(b);
  32656. b.clipTo(a);
  32657. b.invert();
  32658. b.clipTo(a);
  32659. b.invert();
  32660. a.build(b.allPolygons());
  32661. a.invert();
  32662. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32663. };
  32664. CSG.prototype.subtractInPlace = function (csg) {
  32665. var a = new Node(this.polygons);
  32666. var b = new Node(csg.polygons);
  32667. a.invert();
  32668. a.clipTo(b);
  32669. b.clipTo(a);
  32670. b.invert();
  32671. b.clipTo(a);
  32672. b.invert();
  32673. a.build(b.allPolygons());
  32674. a.invert();
  32675. this.polygons = a.allPolygons();
  32676. };
  32677. CSG.prototype.intersect = function (csg) {
  32678. var a = new Node(this.clone().polygons);
  32679. var b = new Node(csg.clone().polygons);
  32680. a.invert();
  32681. b.clipTo(a);
  32682. b.invert();
  32683. a.clipTo(b);
  32684. b.clipTo(a);
  32685. a.build(b.allPolygons());
  32686. a.invert();
  32687. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32688. };
  32689. CSG.prototype.intersectInPlace = function (csg) {
  32690. var a = new Node(this.polygons);
  32691. var b = new Node(csg.polygons);
  32692. a.invert();
  32693. b.clipTo(a);
  32694. b.invert();
  32695. a.clipTo(b);
  32696. b.clipTo(a);
  32697. a.build(b.allPolygons());
  32698. a.invert();
  32699. this.polygons = a.allPolygons();
  32700. };
  32701. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  32702. // not modified.
  32703. CSG.prototype.inverse = function () {
  32704. var csg = this.clone();
  32705. csg.inverseInPlace();
  32706. return csg;
  32707. };
  32708. CSG.prototype.inverseInPlace = function () {
  32709. this.polygons.map(function (p) { p.flip(); });
  32710. };
  32711. // This is used to keep meshes transformations so they can be restored
  32712. // when we build back a Babylon Mesh
  32713. // NB : All CSG operations are performed in world coordinates
  32714. CSG.prototype.copyTransformAttributes = function (csg) {
  32715. this.matrix = csg.matrix;
  32716. this.position = csg.position;
  32717. this.rotation = csg.rotation;
  32718. this.scaling = csg.scaling;
  32719. this.rotationQuaternion = csg.rotationQuaternion;
  32720. return this;
  32721. };
  32722. // Build Raw mesh from CSG
  32723. // Coordinates here are in world space
  32724. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  32725. var matrix = this.matrix.clone();
  32726. matrix.invert();
  32727. 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;
  32728. if (keepSubMeshes) {
  32729. // Sort Polygons, since subMeshes are indices range
  32730. polygons.sort(function (a, b) {
  32731. if (a.shared.meshId === b.shared.meshId) {
  32732. return a.shared.subMeshId - b.shared.subMeshId;
  32733. }
  32734. else {
  32735. return a.shared.meshId - b.shared.meshId;
  32736. }
  32737. });
  32738. }
  32739. for (var i = 0, il = polygons.length; i < il; i++) {
  32740. polygon = polygons[i];
  32741. // Building SubMeshes
  32742. if (!subMesh_dict[polygon.shared.meshId]) {
  32743. subMesh_dict[polygon.shared.meshId] = {};
  32744. }
  32745. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  32746. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  32747. indexStart: +Infinity,
  32748. indexEnd: -Infinity,
  32749. materialIndex: polygon.shared.materialIndex
  32750. };
  32751. }
  32752. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  32753. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32754. polygonIndices[0] = 0;
  32755. polygonIndices[1] = j - 1;
  32756. polygonIndices[2] = j;
  32757. for (var k = 0; k < 3; k++) {
  32758. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32759. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32760. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32761. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32762. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32763. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32764. // Check if 2 points can be merged
  32765. if (!(typeof vertex_idx !== 'undefined' &&
  32766. normals[vertex_idx * 3] === localNormal.x &&
  32767. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32768. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32769. uvs[vertex_idx * 2] === uv.x &&
  32770. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32771. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32772. uvs.push(uv.x, uv.y);
  32773. normals.push(normal.x, normal.y, normal.z);
  32774. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32775. }
  32776. indices.push(vertex_idx);
  32777. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32778. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32779. currentIndex++;
  32780. }
  32781. }
  32782. }
  32783. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32784. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32785. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32786. mesh.setIndices(indices);
  32787. if (keepSubMeshes) {
  32788. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32789. var materialIndexOffset = 0, materialMaxIndex;
  32790. mesh.subMeshes = new Array();
  32791. for (var m in subMesh_dict) {
  32792. materialMaxIndex = -1;
  32793. for (var sm in subMesh_dict[m]) {
  32794. subMesh_obj = subMesh_dict[m][sm];
  32795. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32796. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32797. }
  32798. materialIndexOffset += ++materialMaxIndex;
  32799. }
  32800. }
  32801. return mesh;
  32802. };
  32803. // Build Mesh from CSG taking material and transforms into account
  32804. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32805. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32806. mesh.material = material;
  32807. mesh.position.copyFrom(this.position);
  32808. mesh.rotation.copyFrom(this.rotation);
  32809. if (this.rotationQuaternion) {
  32810. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32811. }
  32812. mesh.scaling.copyFrom(this.scaling);
  32813. mesh.computeWorldMatrix(true);
  32814. return mesh;
  32815. };
  32816. return CSG;
  32817. })();
  32818. BABYLON.CSG = CSG;
  32819. })(BABYLON || (BABYLON = {}));
  32820. var BABYLON;
  32821. (function (BABYLON) {
  32822. var VRDistortionCorrectionPostProcess = (function (_super) {
  32823. __extends(VRDistortionCorrectionPostProcess, _super);
  32824. //ANY
  32825. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  32826. var _this = this;
  32827. _super.call(this, name, "vrDistortionCorrection", [
  32828. 'LensCenter',
  32829. 'Scale',
  32830. 'ScaleIn',
  32831. 'HmdWarpParam'
  32832. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  32833. this._isRightEye = isRightEye;
  32834. this._distortionFactors = vrMetrics.distortionK;
  32835. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  32836. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  32837. this.onSizeChanged = function () {
  32838. _this.aspectRatio = _this.width * .5 / _this.height;
  32839. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  32840. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  32841. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  32842. };
  32843. this.onApply = function (effect) {
  32844. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  32845. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  32846. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  32847. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  32848. };
  32849. }
  32850. return VRDistortionCorrectionPostProcess;
  32851. })(BABYLON.PostProcess);
  32852. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  32853. })(BABYLON || (BABYLON = {}));
  32854. // Mainly based on these 2 articles :
  32855. // 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
  32856. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  32857. var BABYLON;
  32858. (function (BABYLON) {
  32859. (function (JoystickAxis) {
  32860. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  32861. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  32862. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  32863. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  32864. var JoystickAxis = BABYLON.JoystickAxis;
  32865. var VirtualJoystick = (function () {
  32866. function VirtualJoystick(leftJoystick) {
  32867. var _this = this;
  32868. if (leftJoystick) {
  32869. this._leftJoystick = true;
  32870. }
  32871. else {
  32872. this._leftJoystick = false;
  32873. }
  32874. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  32875. VirtualJoystick._globalJoystickIndex++;
  32876. // By default left & right arrow keys are moving the X
  32877. // and up & down keys are moving the Y
  32878. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32879. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32880. this.reverseLeftRight = false;
  32881. this.reverseUpDown = false;
  32882. // collections of pointers
  32883. this._touches = new BABYLON.SmartCollection();
  32884. this.deltaPosition = BABYLON.Vector3.Zero();
  32885. this._joystickSensibility = 25;
  32886. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32887. this._rotationSpeed = 25;
  32888. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  32889. this._rotateOnAxisRelativeToMesh = false;
  32890. this._onResize = function (evt) {
  32891. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32892. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32893. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  32894. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  32895. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  32896. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  32897. };
  32898. // injecting a canvas element on top of the canvas 3D game
  32899. if (!VirtualJoystick.vjCanvas) {
  32900. window.addEventListener("resize", this._onResize, false);
  32901. VirtualJoystick.vjCanvas = document.createElement("canvas");
  32902. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32903. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32904. VirtualJoystick.vjCanvas.width = window.innerWidth;
  32905. VirtualJoystick.vjCanvas.height = window.innerHeight;
  32906. VirtualJoystick.vjCanvas.style.width = "100%";
  32907. VirtualJoystick.vjCanvas.style.height = "100%";
  32908. VirtualJoystick.vjCanvas.style.position = "absolute";
  32909. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  32910. VirtualJoystick.vjCanvas.style.top = "0px";
  32911. VirtualJoystick.vjCanvas.style.left = "0px";
  32912. VirtualJoystick.vjCanvas.style.zIndex = "5";
  32913. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  32914. // Support for jQuery PEP polyfill
  32915. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  32916. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  32917. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  32918. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32919. document.body.appendChild(VirtualJoystick.vjCanvas);
  32920. }
  32921. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  32922. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  32923. this.pressed = false;
  32924. // default joystick color
  32925. this._joystickColor = "cyan";
  32926. this._joystickPointerID = -1;
  32927. // current joystick position
  32928. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  32929. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  32930. // origin joystick position
  32931. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  32932. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  32933. this._onPointerDownHandlerRef = function (evt) {
  32934. _this._onPointerDown(evt);
  32935. };
  32936. this._onPointerMoveHandlerRef = function (evt) {
  32937. _this._onPointerMove(evt);
  32938. };
  32939. this._onPointerOutHandlerRef = function (evt) {
  32940. _this._onPointerUp(evt);
  32941. };
  32942. this._onPointerUpHandlerRef = function (evt) {
  32943. _this._onPointerUp(evt);
  32944. };
  32945. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  32946. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  32947. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  32948. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  32949. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  32950. evt.preventDefault(); // Disables system menu
  32951. }, false);
  32952. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32953. }
  32954. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  32955. this._joystickSensibility = newJoystickSensibility;
  32956. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32957. };
  32958. VirtualJoystick.prototype._onPointerDown = function (e) {
  32959. var positionOnScreenCondition;
  32960. e.preventDefault();
  32961. if (this._leftJoystick === true) {
  32962. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  32963. }
  32964. else {
  32965. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  32966. }
  32967. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  32968. // First contact will be dedicated to the virtual joystick
  32969. this._joystickPointerID = e.pointerId;
  32970. this._joystickPointerStartPos.x = e.clientX;
  32971. this._joystickPointerStartPos.y = e.clientY;
  32972. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  32973. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  32974. this._deltaJoystickVector.x = 0;
  32975. this._deltaJoystickVector.y = 0;
  32976. this.pressed = true;
  32977. this._touches.add(e.pointerId.toString(), e);
  32978. }
  32979. else {
  32980. // You can only trigger the action buttons with a joystick declared
  32981. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  32982. this._action();
  32983. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  32984. }
  32985. }
  32986. };
  32987. VirtualJoystick.prototype._onPointerMove = function (e) {
  32988. // If the current pointer is the one associated to the joystick (first touch contact)
  32989. if (this._joystickPointerID == e.pointerId) {
  32990. this._joystickPointerPos.x = e.clientX;
  32991. this._joystickPointerPos.y = e.clientY;
  32992. this._deltaJoystickVector = this._joystickPointerPos.clone();
  32993. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  32994. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  32995. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  32996. switch (this._axisTargetedByLeftAndRight) {
  32997. case JoystickAxis.X:
  32998. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  32999. break;
  33000. case JoystickAxis.Y:
  33001. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  33002. break;
  33003. case JoystickAxis.Z:
  33004. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  33005. break;
  33006. }
  33007. var directionUpDown = this.reverseUpDown ? 1 : -1;
  33008. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  33009. switch (this._axisTargetedByUpAndDown) {
  33010. case JoystickAxis.X:
  33011. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  33012. break;
  33013. case JoystickAxis.Y:
  33014. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  33015. break;
  33016. case JoystickAxis.Z:
  33017. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  33018. break;
  33019. }
  33020. }
  33021. else {
  33022. if (this._touches.item(e.pointerId.toString())) {
  33023. this._touches.item(e.pointerId.toString()).x = e.clientX;
  33024. this._touches.item(e.pointerId.toString()).y = e.clientY;
  33025. }
  33026. }
  33027. };
  33028. VirtualJoystick.prototype._onPointerUp = function (e) {
  33029. if (this._joystickPointerID == e.pointerId) {
  33030. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  33031. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  33032. this._joystickPointerID = -1;
  33033. this.pressed = false;
  33034. }
  33035. else {
  33036. var touch = this._touches.item(e.pointerId.toString());
  33037. if (touch) {
  33038. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33039. }
  33040. }
  33041. this._deltaJoystickVector.x = 0;
  33042. this._deltaJoystickVector.y = 0;
  33043. this._touches.remove(e.pointerId.toString());
  33044. };
  33045. /**
  33046. * Change the color of the virtual joystick
  33047. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  33048. */
  33049. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  33050. this._joystickColor = newColor;
  33051. };
  33052. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  33053. this._action = action;
  33054. };
  33055. // Define which axis you'd like to control for left & right
  33056. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  33057. switch (axis) {
  33058. case JoystickAxis.X:
  33059. case JoystickAxis.Y:
  33060. case JoystickAxis.Z:
  33061. this._axisTargetedByLeftAndRight = axis;
  33062. break;
  33063. default:
  33064. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33065. break;
  33066. }
  33067. };
  33068. // Define which axis you'd like to control for up & down
  33069. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  33070. switch (axis) {
  33071. case JoystickAxis.X:
  33072. case JoystickAxis.Y:
  33073. case JoystickAxis.Z:
  33074. this._axisTargetedByUpAndDown = axis;
  33075. break;
  33076. default:
  33077. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33078. break;
  33079. }
  33080. };
  33081. VirtualJoystick.prototype._clearCanvas = function () {
  33082. if (this._leftJoystick) {
  33083. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  33084. }
  33085. else {
  33086. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  33087. }
  33088. };
  33089. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  33090. var _this = this;
  33091. if (this.pressed) {
  33092. this._touches.forEach(function (touch) {
  33093. if (touch.pointerId === _this._joystickPointerID) {
  33094. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  33095. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  33096. VirtualJoystick.vjCanvasContext.beginPath();
  33097. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33098. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33099. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  33100. VirtualJoystick.vjCanvasContext.stroke();
  33101. VirtualJoystick.vjCanvasContext.closePath();
  33102. VirtualJoystick.vjCanvasContext.beginPath();
  33103. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33104. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33105. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  33106. VirtualJoystick.vjCanvasContext.stroke();
  33107. VirtualJoystick.vjCanvasContext.closePath();
  33108. VirtualJoystick.vjCanvasContext.beginPath();
  33109. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33110. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  33111. VirtualJoystick.vjCanvasContext.stroke();
  33112. VirtualJoystick.vjCanvasContext.closePath();
  33113. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  33114. }
  33115. else {
  33116. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33117. VirtualJoystick.vjCanvasContext.beginPath();
  33118. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  33119. VirtualJoystick.vjCanvasContext.beginPath();
  33120. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  33121. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33122. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  33123. VirtualJoystick.vjCanvasContext.stroke();
  33124. VirtualJoystick.vjCanvasContext.closePath();
  33125. touch.prevX = touch.x;
  33126. touch.prevY = touch.y;
  33127. }
  33128. ;
  33129. });
  33130. }
  33131. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33132. };
  33133. VirtualJoystick.prototype.releaseCanvas = function () {
  33134. if (VirtualJoystick.vjCanvas) {
  33135. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  33136. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  33137. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  33138. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  33139. window.removeEventListener("resize", this._onResize);
  33140. document.body.removeChild(VirtualJoystick.vjCanvas);
  33141. VirtualJoystick.vjCanvas = null;
  33142. }
  33143. };
  33144. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  33145. VirtualJoystick._globalJoystickIndex = 0;
  33146. return VirtualJoystick;
  33147. })();
  33148. BABYLON.VirtualJoystick = VirtualJoystick;
  33149. })(BABYLON || (BABYLON = {}));
  33150. var BABYLON;
  33151. (function (BABYLON) {
  33152. // We're mainly based on the logic defined into the FreeCamera code
  33153. var VirtualJoysticksCamera = (function (_super) {
  33154. __extends(VirtualJoysticksCamera, _super);
  33155. function VirtualJoysticksCamera(name, position, scene) {
  33156. _super.call(this, name, position, scene);
  33157. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  33158. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  33159. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  33160. this._leftjoystick.setJoystickSensibility(0.15);
  33161. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  33162. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  33163. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  33164. this._rightjoystick.reverseUpDown = true;
  33165. this._rightjoystick.setJoystickSensibility(0.05);
  33166. this._rightjoystick.setJoystickColor("yellow");
  33167. }
  33168. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  33169. return this._leftjoystick;
  33170. };
  33171. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  33172. return this._rightjoystick;
  33173. };
  33174. VirtualJoysticksCamera.prototype._checkInputs = function () {
  33175. var speed = this._computeLocalCameraSpeed() * 50;
  33176. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33177. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  33178. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33179. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  33180. if (!this._leftjoystick.pressed) {
  33181. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  33182. }
  33183. if (!this._rightjoystick.pressed) {
  33184. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  33185. }
  33186. _super.prototype._checkInputs.call(this);
  33187. };
  33188. VirtualJoysticksCamera.prototype.dispose = function () {
  33189. this._leftjoystick.releaseCanvas();
  33190. _super.prototype.dispose.call(this);
  33191. };
  33192. VirtualJoysticksCamera.prototype.getTypeName = function () {
  33193. return "VirtualJoysticksCamera";
  33194. };
  33195. return VirtualJoysticksCamera;
  33196. })(BABYLON.FreeCamera);
  33197. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  33198. })(BABYLON || (BABYLON = {}));
  33199. var BABYLON;
  33200. (function (BABYLON) {
  33201. var AnaglyphPostProcess = (function (_super) {
  33202. __extends(AnaglyphPostProcess, _super);
  33203. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33204. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  33205. }
  33206. return AnaglyphPostProcess;
  33207. })(BABYLON.PostProcess);
  33208. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  33209. })(BABYLON || (BABYLON = {}));
  33210. var BABYLON;
  33211. (function (BABYLON) {
  33212. var OutlineRenderer = (function () {
  33213. function OutlineRenderer(scene) {
  33214. this._scene = scene;
  33215. }
  33216. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  33217. var _this = this;
  33218. if (useOverlay === void 0) { useOverlay = false; }
  33219. var scene = this._scene;
  33220. var engine = this._scene.getEngine();
  33221. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33222. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  33223. return;
  33224. }
  33225. var mesh = subMesh.getRenderingMesh();
  33226. var material = subMesh.getMaterial();
  33227. engine.enableEffect(this._effect);
  33228. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  33229. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  33230. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33231. // Bones
  33232. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33233. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33234. }
  33235. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33236. // Alpha test
  33237. if (material && material.needAlphaTesting()) {
  33238. var alphaTexture = material.getAlphaTestTexture();
  33239. this._effect.setTexture("diffuseSampler", alphaTexture);
  33240. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33241. }
  33242. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  33243. };
  33244. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  33245. var defines = [];
  33246. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  33247. var mesh = subMesh.getMesh();
  33248. var material = subMesh.getMaterial();
  33249. // Alpha test
  33250. if (material && material.needAlphaTesting()) {
  33251. defines.push("#define ALPHATEST");
  33252. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33253. attribs.push(BABYLON.VertexBuffer.UVKind);
  33254. defines.push("#define UV1");
  33255. }
  33256. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33257. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33258. defines.push("#define UV2");
  33259. }
  33260. }
  33261. // Bones
  33262. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33263. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33264. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33265. if (mesh.numBoneInfluencers > 4) {
  33266. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33267. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33268. }
  33269. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33270. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33271. }
  33272. else {
  33273. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33274. }
  33275. // Instances
  33276. if (useInstances) {
  33277. defines.push("#define INSTANCES");
  33278. attribs.push("world0");
  33279. attribs.push("world1");
  33280. attribs.push("world2");
  33281. attribs.push("world3");
  33282. }
  33283. // Get correct effect
  33284. var join = defines.join("\n");
  33285. if (this._cachedDefines !== join) {
  33286. this._cachedDefines = join;
  33287. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  33288. }
  33289. return this._effect.isReady();
  33290. };
  33291. return OutlineRenderer;
  33292. })();
  33293. BABYLON.OutlineRenderer = OutlineRenderer;
  33294. })(BABYLON || (BABYLON = {}));
  33295. var BABYLON;
  33296. (function (BABYLON) {
  33297. var MeshAssetTask = (function () {
  33298. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  33299. this.name = name;
  33300. this.meshesNames = meshesNames;
  33301. this.rootUrl = rootUrl;
  33302. this.sceneFilename = sceneFilename;
  33303. this.isCompleted = false;
  33304. }
  33305. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33306. var _this = this;
  33307. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  33308. _this.loadedMeshes = meshes;
  33309. _this.loadedParticleSystems = particleSystems;
  33310. _this.loadedSkeletons = skeletons;
  33311. _this.isCompleted = true;
  33312. if (_this.onSuccess) {
  33313. _this.onSuccess(_this);
  33314. }
  33315. onSuccess();
  33316. }, null, function () {
  33317. if (_this.onError) {
  33318. _this.onError(_this);
  33319. }
  33320. onError();
  33321. });
  33322. };
  33323. return MeshAssetTask;
  33324. })();
  33325. BABYLON.MeshAssetTask = MeshAssetTask;
  33326. var TextFileAssetTask = (function () {
  33327. function TextFileAssetTask(name, url) {
  33328. this.name = name;
  33329. this.url = url;
  33330. this.isCompleted = false;
  33331. }
  33332. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33333. var _this = this;
  33334. BABYLON.Tools.LoadFile(this.url, function (data) {
  33335. _this.text = data;
  33336. _this.isCompleted = true;
  33337. if (_this.onSuccess) {
  33338. _this.onSuccess(_this);
  33339. }
  33340. onSuccess();
  33341. }, null, scene.database, false, function () {
  33342. if (_this.onError) {
  33343. _this.onError(_this);
  33344. }
  33345. onError();
  33346. });
  33347. };
  33348. return TextFileAssetTask;
  33349. })();
  33350. BABYLON.TextFileAssetTask = TextFileAssetTask;
  33351. var BinaryFileAssetTask = (function () {
  33352. function BinaryFileAssetTask(name, url) {
  33353. this.name = name;
  33354. this.url = url;
  33355. this.isCompleted = false;
  33356. }
  33357. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33358. var _this = this;
  33359. BABYLON.Tools.LoadFile(this.url, function (data) {
  33360. _this.data = data;
  33361. _this.isCompleted = true;
  33362. if (_this.onSuccess) {
  33363. _this.onSuccess(_this);
  33364. }
  33365. onSuccess();
  33366. }, null, scene.database, true, function () {
  33367. if (_this.onError) {
  33368. _this.onError(_this);
  33369. }
  33370. onError();
  33371. });
  33372. };
  33373. return BinaryFileAssetTask;
  33374. })();
  33375. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  33376. var ImageAssetTask = (function () {
  33377. function ImageAssetTask(name, url) {
  33378. this.name = name;
  33379. this.url = url;
  33380. this.isCompleted = false;
  33381. }
  33382. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33383. var _this = this;
  33384. var img = new Image();
  33385. img.onload = function () {
  33386. _this.image = img;
  33387. _this.isCompleted = true;
  33388. if (_this.onSuccess) {
  33389. _this.onSuccess(_this);
  33390. }
  33391. onSuccess();
  33392. };
  33393. img.onerror = function () {
  33394. if (_this.onError) {
  33395. _this.onError(_this);
  33396. }
  33397. onError();
  33398. };
  33399. img.src = this.url;
  33400. };
  33401. return ImageAssetTask;
  33402. })();
  33403. BABYLON.ImageAssetTask = ImageAssetTask;
  33404. var TextureAssetTask = (function () {
  33405. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  33406. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33407. this.name = name;
  33408. this.url = url;
  33409. this.noMipmap = noMipmap;
  33410. this.invertY = invertY;
  33411. this.samplingMode = samplingMode;
  33412. this.isCompleted = false;
  33413. }
  33414. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33415. var _this = this;
  33416. var onload = function () {
  33417. _this.isCompleted = true;
  33418. if (_this.onSuccess) {
  33419. _this.onSuccess(_this);
  33420. }
  33421. onSuccess();
  33422. };
  33423. var onerror = function () {
  33424. if (_this.onError) {
  33425. _this.onError(_this);
  33426. }
  33427. onError();
  33428. };
  33429. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  33430. };
  33431. return TextureAssetTask;
  33432. })();
  33433. BABYLON.TextureAssetTask = TextureAssetTask;
  33434. var AssetsManager = (function () {
  33435. function AssetsManager(scene) {
  33436. this._tasks = new Array();
  33437. this._waitingTasksCount = 0;
  33438. this.useDefaultLoadingScreen = true;
  33439. this._scene = scene;
  33440. }
  33441. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  33442. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  33443. this._tasks.push(task);
  33444. return task;
  33445. };
  33446. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  33447. var task = new TextFileAssetTask(taskName, url);
  33448. this._tasks.push(task);
  33449. return task;
  33450. };
  33451. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  33452. var task = new BinaryFileAssetTask(taskName, url);
  33453. this._tasks.push(task);
  33454. return task;
  33455. };
  33456. AssetsManager.prototype.addImageTask = function (taskName, url) {
  33457. var task = new ImageAssetTask(taskName, url);
  33458. this._tasks.push(task);
  33459. return task;
  33460. };
  33461. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  33462. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33463. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  33464. this._tasks.push(task);
  33465. return task;
  33466. };
  33467. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  33468. this._waitingTasksCount--;
  33469. if (this._waitingTasksCount === 0) {
  33470. if (this.onFinish) {
  33471. this.onFinish(this._tasks);
  33472. }
  33473. this._scene.getEngine().hideLoadingUI();
  33474. }
  33475. };
  33476. AssetsManager.prototype._runTask = function (task) {
  33477. var _this = this;
  33478. task.run(this._scene, function () {
  33479. if (_this.onTaskSuccess) {
  33480. _this.onTaskSuccess(task);
  33481. }
  33482. _this._decreaseWaitingTasksCount();
  33483. }, function () {
  33484. if (_this.onTaskError) {
  33485. _this.onTaskError(task);
  33486. }
  33487. _this._decreaseWaitingTasksCount();
  33488. });
  33489. };
  33490. AssetsManager.prototype.reset = function () {
  33491. this._tasks = new Array();
  33492. return this;
  33493. };
  33494. AssetsManager.prototype.load = function () {
  33495. this._waitingTasksCount = this._tasks.length;
  33496. if (this._waitingTasksCount === 0) {
  33497. if (this.onFinish) {
  33498. this.onFinish(this._tasks);
  33499. }
  33500. return this;
  33501. }
  33502. if (this.useDefaultLoadingScreen) {
  33503. this._scene.getEngine().displayLoadingUI();
  33504. }
  33505. for (var index = 0; index < this._tasks.length; index++) {
  33506. var task = this._tasks[index];
  33507. this._runTask(task);
  33508. }
  33509. return this;
  33510. };
  33511. return AssetsManager;
  33512. })();
  33513. BABYLON.AssetsManager = AssetsManager;
  33514. })(BABYLON || (BABYLON = {}));
  33515. var BABYLON;
  33516. (function (BABYLON) {
  33517. var VRCameraMetrics = (function () {
  33518. function VRCameraMetrics() {
  33519. this.compensateDistortion = true;
  33520. }
  33521. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  33522. get: function () {
  33523. return this.hResolution / (2 * this.vResolution);
  33524. },
  33525. enumerable: true,
  33526. configurable: true
  33527. });
  33528. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  33529. get: function () {
  33530. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  33531. },
  33532. enumerable: true,
  33533. configurable: true
  33534. });
  33535. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  33536. get: function () {
  33537. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33538. var h = (4 * meters) / this.hScreenSize;
  33539. return BABYLON.Matrix.Translation(h, 0, 0);
  33540. },
  33541. enumerable: true,
  33542. configurable: true
  33543. });
  33544. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  33545. get: function () {
  33546. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33547. var h = (4 * meters) / this.hScreenSize;
  33548. return BABYLON.Matrix.Translation(-h, 0, 0);
  33549. },
  33550. enumerable: true,
  33551. configurable: true
  33552. });
  33553. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  33554. get: function () {
  33555. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  33556. },
  33557. enumerable: true,
  33558. configurable: true
  33559. });
  33560. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  33561. get: function () {
  33562. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  33563. },
  33564. enumerable: true,
  33565. configurable: true
  33566. });
  33567. VRCameraMetrics.GetDefault = function () {
  33568. var result = new VRCameraMetrics();
  33569. result.hResolution = 1280;
  33570. result.vResolution = 800;
  33571. result.hScreenSize = 0.149759993;
  33572. result.vScreenSize = 0.0935999975;
  33573. result.vScreenCenter = 0.0467999987,
  33574. result.eyeToScreenDistance = 0.0410000011;
  33575. result.lensSeparationDistance = 0.0635000020;
  33576. result.interpupillaryDistance = 0.0640000030;
  33577. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  33578. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  33579. result.postProcessScaleFactor = 1.714605507808412;
  33580. result.lensCenterOffset = 0.151976421;
  33581. return result;
  33582. };
  33583. return VRCameraMetrics;
  33584. })();
  33585. BABYLON.VRCameraMetrics = VRCameraMetrics;
  33586. })(BABYLON || (BABYLON = {}));
  33587. var BABYLON;
  33588. (function (BABYLON) {
  33589. var VRDeviceOrientationFreeCamera = (function (_super) {
  33590. __extends(VRDeviceOrientationFreeCamera, _super);
  33591. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  33592. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33593. _super.call(this, name, position, scene);
  33594. this._alpha = 0;
  33595. this._beta = 0;
  33596. this._gamma = 0;
  33597. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33598. metrics.compensateDistortion = compensateDistortion;
  33599. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33600. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  33601. }
  33602. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  33603. this._alpha = +evt.alpha | 0;
  33604. this._beta = +evt.beta | 0;
  33605. this._gamma = +evt.gamma | 0;
  33606. if (this._gamma < 0) {
  33607. this._gamma = 90 + this._gamma;
  33608. }
  33609. else {
  33610. // Incline it in the correct angle.
  33611. this._gamma = 270 - this._gamma;
  33612. }
  33613. this.rotation.x = this._gamma / 180.0 * Math.PI;
  33614. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  33615. this.rotation.z = this._beta / 180.0 * Math.PI;
  33616. };
  33617. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33618. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33619. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  33620. };
  33621. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  33622. _super.prototype.detachControl.call(this, element);
  33623. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  33624. };
  33625. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  33626. return "VRDeviceOrientationFreeCamera";
  33627. };
  33628. return VRDeviceOrientationFreeCamera;
  33629. })(BABYLON.FreeCamera);
  33630. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  33631. })(BABYLON || (BABYLON = {}));
  33632. var BABYLON;
  33633. (function (BABYLON) {
  33634. var WebVRFreeCamera = (function (_super) {
  33635. __extends(WebVRFreeCamera, _super);
  33636. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  33637. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33638. _super.call(this, name, position, scene);
  33639. this._hmdDevice = null;
  33640. this._sensorDevice = null;
  33641. this._cacheState = null;
  33642. this._cacheQuaternion = new BABYLON.Quaternion();
  33643. this._cacheRotation = BABYLON.Vector3.Zero();
  33644. this._vrEnabled = false;
  33645. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33646. metrics.compensateDistortion = compensateDistortion;
  33647. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33648. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  33649. }
  33650. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  33651. var size = devices.length;
  33652. var i = 0;
  33653. // Reset devices.
  33654. this._sensorDevice = null;
  33655. this._hmdDevice = null;
  33656. // Search for a HmdDevice.
  33657. while (i < size && this._hmdDevice === null) {
  33658. if (devices[i] instanceof HMDVRDevice) {
  33659. this._hmdDevice = devices[i];
  33660. }
  33661. i++;
  33662. }
  33663. i = 0;
  33664. while (i < size && this._sensorDevice === null) {
  33665. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  33666. this._sensorDevice = devices[i];
  33667. }
  33668. i++;
  33669. }
  33670. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  33671. };
  33672. WebVRFreeCamera.prototype._checkInputs = function () {
  33673. if (this._vrEnabled) {
  33674. this._cacheState = this._sensorDevice.getState();
  33675. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  33676. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  33677. this.rotation.x = -this._cacheRotation.z;
  33678. this.rotation.y = -this._cacheRotation.y;
  33679. this.rotation.z = this._cacheRotation.x;
  33680. }
  33681. _super.prototype._checkInputs.call(this);
  33682. };
  33683. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33684. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33685. if (navigator.getVRDevices) {
  33686. navigator.getVRDevices().then(this._getWebVRDevices);
  33687. }
  33688. else if (navigator.mozGetVRDevices) {
  33689. navigator.mozGetVRDevices(this._getWebVRDevices);
  33690. }
  33691. };
  33692. WebVRFreeCamera.prototype.detachControl = function (element) {
  33693. _super.prototype.detachControl.call(this, element);
  33694. this._vrEnabled = false;
  33695. };
  33696. WebVRFreeCamera.prototype.getTypeName = function () {
  33697. return "WebVRFreeCamera";
  33698. };
  33699. return WebVRFreeCamera;
  33700. })(BABYLON.FreeCamera);
  33701. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  33702. })(BABYLON || (BABYLON = {}));
  33703. var BABYLON;
  33704. (function (BABYLON) {
  33705. // Standard optimizations
  33706. var SceneOptimization = (function () {
  33707. function SceneOptimization(priority) {
  33708. if (priority === void 0) { priority = 0; }
  33709. this.priority = priority;
  33710. this.apply = function (scene) {
  33711. return true; // Return true if everything that can be done was applied
  33712. };
  33713. }
  33714. return SceneOptimization;
  33715. })();
  33716. BABYLON.SceneOptimization = SceneOptimization;
  33717. var TextureOptimization = (function (_super) {
  33718. __extends(TextureOptimization, _super);
  33719. function TextureOptimization(priority, maximumSize) {
  33720. var _this = this;
  33721. if (priority === void 0) { priority = 0; }
  33722. if (maximumSize === void 0) { maximumSize = 1024; }
  33723. _super.call(this, priority);
  33724. this.priority = priority;
  33725. this.maximumSize = maximumSize;
  33726. this.apply = function (scene) {
  33727. var allDone = true;
  33728. for (var index = 0; index < scene.textures.length; index++) {
  33729. var texture = scene.textures[index];
  33730. if (!texture.canRescale) {
  33731. continue;
  33732. }
  33733. var currentSize = texture.getSize();
  33734. var maxDimension = Math.max(currentSize.width, currentSize.height);
  33735. if (maxDimension > _this.maximumSize) {
  33736. texture.scale(0.5);
  33737. allDone = false;
  33738. }
  33739. }
  33740. return allDone;
  33741. };
  33742. }
  33743. return TextureOptimization;
  33744. })(SceneOptimization);
  33745. BABYLON.TextureOptimization = TextureOptimization;
  33746. var HardwareScalingOptimization = (function (_super) {
  33747. __extends(HardwareScalingOptimization, _super);
  33748. function HardwareScalingOptimization(priority, maximumScale) {
  33749. var _this = this;
  33750. if (priority === void 0) { priority = 0; }
  33751. if (maximumScale === void 0) { maximumScale = 2; }
  33752. _super.call(this, priority);
  33753. this.priority = priority;
  33754. this.maximumScale = maximumScale;
  33755. this._currentScale = 1;
  33756. this.apply = function (scene) {
  33757. _this._currentScale++;
  33758. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  33759. return _this._currentScale >= _this.maximumScale;
  33760. };
  33761. }
  33762. return HardwareScalingOptimization;
  33763. })(SceneOptimization);
  33764. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  33765. var ShadowsOptimization = (function (_super) {
  33766. __extends(ShadowsOptimization, _super);
  33767. function ShadowsOptimization() {
  33768. _super.apply(this, arguments);
  33769. this.apply = function (scene) {
  33770. scene.shadowsEnabled = false;
  33771. return true;
  33772. };
  33773. }
  33774. return ShadowsOptimization;
  33775. })(SceneOptimization);
  33776. BABYLON.ShadowsOptimization = ShadowsOptimization;
  33777. var PostProcessesOptimization = (function (_super) {
  33778. __extends(PostProcessesOptimization, _super);
  33779. function PostProcessesOptimization() {
  33780. _super.apply(this, arguments);
  33781. this.apply = function (scene) {
  33782. scene.postProcessesEnabled = false;
  33783. return true;
  33784. };
  33785. }
  33786. return PostProcessesOptimization;
  33787. })(SceneOptimization);
  33788. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  33789. var LensFlaresOptimization = (function (_super) {
  33790. __extends(LensFlaresOptimization, _super);
  33791. function LensFlaresOptimization() {
  33792. _super.apply(this, arguments);
  33793. this.apply = function (scene) {
  33794. scene.lensFlaresEnabled = false;
  33795. return true;
  33796. };
  33797. }
  33798. return LensFlaresOptimization;
  33799. })(SceneOptimization);
  33800. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  33801. var ParticlesOptimization = (function (_super) {
  33802. __extends(ParticlesOptimization, _super);
  33803. function ParticlesOptimization() {
  33804. _super.apply(this, arguments);
  33805. this.apply = function (scene) {
  33806. scene.particlesEnabled = false;
  33807. return true;
  33808. };
  33809. }
  33810. return ParticlesOptimization;
  33811. })(SceneOptimization);
  33812. BABYLON.ParticlesOptimization = ParticlesOptimization;
  33813. var RenderTargetsOptimization = (function (_super) {
  33814. __extends(RenderTargetsOptimization, _super);
  33815. function RenderTargetsOptimization() {
  33816. _super.apply(this, arguments);
  33817. this.apply = function (scene) {
  33818. scene.renderTargetsEnabled = false;
  33819. return true;
  33820. };
  33821. }
  33822. return RenderTargetsOptimization;
  33823. })(SceneOptimization);
  33824. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  33825. var MergeMeshesOptimization = (function (_super) {
  33826. __extends(MergeMeshesOptimization, _super);
  33827. function MergeMeshesOptimization() {
  33828. var _this = this;
  33829. _super.apply(this, arguments);
  33830. this._canBeMerged = function (abstractMesh) {
  33831. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  33832. return false;
  33833. }
  33834. var mesh = abstractMesh;
  33835. if (!mesh.isVisible || !mesh.isEnabled()) {
  33836. return false;
  33837. }
  33838. if (mesh.instances.length > 0) {
  33839. return false;
  33840. }
  33841. if (mesh.skeleton || mesh.hasLODLevels) {
  33842. return false;
  33843. }
  33844. if (mesh.parent) {
  33845. return false;
  33846. }
  33847. return true;
  33848. };
  33849. this.apply = function (scene, updateSelectionTree) {
  33850. var globalPool = scene.meshes.slice(0);
  33851. var globalLength = globalPool.length;
  33852. for (var index = 0; index < globalLength; index++) {
  33853. var currentPool = new Array();
  33854. var current = globalPool[index];
  33855. // Checks
  33856. if (!_this._canBeMerged(current)) {
  33857. continue;
  33858. }
  33859. currentPool.push(current);
  33860. // Find compatible meshes
  33861. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  33862. var otherMesh = globalPool[subIndex];
  33863. if (!_this._canBeMerged(otherMesh)) {
  33864. continue;
  33865. }
  33866. if (otherMesh.material !== current.material) {
  33867. continue;
  33868. }
  33869. if (otherMesh.checkCollisions !== current.checkCollisions) {
  33870. continue;
  33871. }
  33872. currentPool.push(otherMesh);
  33873. globalLength--;
  33874. globalPool.splice(subIndex, 1);
  33875. subIndex--;
  33876. }
  33877. if (currentPool.length < 2) {
  33878. continue;
  33879. }
  33880. // Merge meshes
  33881. BABYLON.Mesh.MergeMeshes(currentPool);
  33882. }
  33883. if (updateSelectionTree != undefined) {
  33884. if (updateSelectionTree) {
  33885. scene.createOrUpdateSelectionOctree();
  33886. }
  33887. }
  33888. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  33889. scene.createOrUpdateSelectionOctree();
  33890. }
  33891. return true;
  33892. };
  33893. }
  33894. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  33895. get: function () {
  33896. return MergeMeshesOptimization._UpdateSelectionTree;
  33897. },
  33898. set: function (value) {
  33899. MergeMeshesOptimization._UpdateSelectionTree = value;
  33900. },
  33901. enumerable: true,
  33902. configurable: true
  33903. });
  33904. MergeMeshesOptimization._UpdateSelectionTree = false;
  33905. return MergeMeshesOptimization;
  33906. })(SceneOptimization);
  33907. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  33908. // Options
  33909. var SceneOptimizerOptions = (function () {
  33910. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  33911. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  33912. if (trackerDuration === void 0) { trackerDuration = 2000; }
  33913. this.targetFrameRate = targetFrameRate;
  33914. this.trackerDuration = trackerDuration;
  33915. this.optimizations = new Array();
  33916. }
  33917. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  33918. var result = new SceneOptimizerOptions(targetFrameRate);
  33919. var priority = 0;
  33920. result.optimizations.push(new MergeMeshesOptimization(priority));
  33921. result.optimizations.push(new ShadowsOptimization(priority));
  33922. result.optimizations.push(new LensFlaresOptimization(priority));
  33923. // Next priority
  33924. priority++;
  33925. result.optimizations.push(new PostProcessesOptimization(priority));
  33926. result.optimizations.push(new ParticlesOptimization(priority));
  33927. // Next priority
  33928. priority++;
  33929. result.optimizations.push(new TextureOptimization(priority, 1024));
  33930. return result;
  33931. };
  33932. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  33933. var result = new SceneOptimizerOptions(targetFrameRate);
  33934. var priority = 0;
  33935. result.optimizations.push(new MergeMeshesOptimization(priority));
  33936. result.optimizations.push(new ShadowsOptimization(priority));
  33937. result.optimizations.push(new LensFlaresOptimization(priority));
  33938. // Next priority
  33939. priority++;
  33940. result.optimizations.push(new PostProcessesOptimization(priority));
  33941. result.optimizations.push(new ParticlesOptimization(priority));
  33942. // Next priority
  33943. priority++;
  33944. result.optimizations.push(new TextureOptimization(priority, 512));
  33945. // Next priority
  33946. priority++;
  33947. result.optimizations.push(new RenderTargetsOptimization(priority));
  33948. // Next priority
  33949. priority++;
  33950. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  33951. return result;
  33952. };
  33953. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  33954. var result = new SceneOptimizerOptions(targetFrameRate);
  33955. var priority = 0;
  33956. result.optimizations.push(new MergeMeshesOptimization(priority));
  33957. result.optimizations.push(new ShadowsOptimization(priority));
  33958. result.optimizations.push(new LensFlaresOptimization(priority));
  33959. // Next priority
  33960. priority++;
  33961. result.optimizations.push(new PostProcessesOptimization(priority));
  33962. result.optimizations.push(new ParticlesOptimization(priority));
  33963. // Next priority
  33964. priority++;
  33965. result.optimizations.push(new TextureOptimization(priority, 256));
  33966. // Next priority
  33967. priority++;
  33968. result.optimizations.push(new RenderTargetsOptimization(priority));
  33969. // Next priority
  33970. priority++;
  33971. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  33972. return result;
  33973. };
  33974. return SceneOptimizerOptions;
  33975. })();
  33976. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  33977. // Scene optimizer tool
  33978. var SceneOptimizer = (function () {
  33979. function SceneOptimizer() {
  33980. }
  33981. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  33982. // TODO: add an epsilon
  33983. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  33984. if (onSuccess) {
  33985. onSuccess();
  33986. }
  33987. return;
  33988. }
  33989. // Apply current level of optimizations
  33990. var allDone = true;
  33991. var noOptimizationApplied = true;
  33992. for (var index = 0; index < options.optimizations.length; index++) {
  33993. var optimization = options.optimizations[index];
  33994. if (optimization.priority === currentPriorityLevel) {
  33995. noOptimizationApplied = false;
  33996. allDone = allDone && optimization.apply(scene);
  33997. }
  33998. }
  33999. // If no optimization was applied, this is a failure :(
  34000. if (noOptimizationApplied) {
  34001. if (onFailure) {
  34002. onFailure();
  34003. }
  34004. return;
  34005. }
  34006. // If all optimizations were done, move to next level
  34007. if (allDone) {
  34008. currentPriorityLevel++;
  34009. }
  34010. // Let's the system running for a specific amount of time before checking FPS
  34011. scene.executeWhenReady(function () {
  34012. setTimeout(function () {
  34013. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  34014. }, options.trackerDuration);
  34015. });
  34016. };
  34017. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  34018. if (!options) {
  34019. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  34020. }
  34021. // Let's the system running for a specific amount of time before checking FPS
  34022. scene.executeWhenReady(function () {
  34023. setTimeout(function () {
  34024. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  34025. }, options.trackerDuration);
  34026. });
  34027. };
  34028. return SceneOptimizer;
  34029. })();
  34030. BABYLON.SceneOptimizer = SceneOptimizer;
  34031. })(BABYLON || (BABYLON = {}));
  34032. var BABYLON;
  34033. (function (BABYLON) {
  34034. var Internals;
  34035. (function (Internals) {
  34036. var MeshLODLevel = (function () {
  34037. function MeshLODLevel(distance, mesh) {
  34038. this.distance = distance;
  34039. this.mesh = mesh;
  34040. }
  34041. return MeshLODLevel;
  34042. })();
  34043. Internals.MeshLODLevel = MeshLODLevel;
  34044. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34045. })(BABYLON || (BABYLON = {}));
  34046. var BABYLON;
  34047. (function (BABYLON) {
  34048. var RawTexture = (function (_super) {
  34049. __extends(RawTexture, _super);
  34050. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34051. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34052. if (invertY === void 0) { invertY = false; }
  34053. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34054. _super.call(this, null, scene, !generateMipMaps, invertY);
  34055. this.format = format;
  34056. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34057. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34058. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34059. }
  34060. RawTexture.prototype.update = function (data) {
  34061. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34062. };
  34063. // Statics
  34064. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34065. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34066. if (invertY === void 0) { invertY = false; }
  34067. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34068. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34069. };
  34070. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34071. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34072. if (invertY === void 0) { invertY = false; }
  34073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34074. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34075. };
  34076. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34077. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34078. if (invertY === void 0) { invertY = false; }
  34079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34080. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34081. };
  34082. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34083. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34084. if (invertY === void 0) { invertY = false; }
  34085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34086. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34087. };
  34088. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34089. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34090. if (invertY === void 0) { invertY = false; }
  34091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34092. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34093. };
  34094. return RawTexture;
  34095. })(BABYLON.Texture);
  34096. BABYLON.RawTexture = RawTexture;
  34097. })(BABYLON || (BABYLON = {}));
  34098. var BABYLON;
  34099. (function (BABYLON) {
  34100. var IndexedVector2 = (function (_super) {
  34101. __extends(IndexedVector2, _super);
  34102. function IndexedVector2(original, index) {
  34103. _super.call(this, original.x, original.y);
  34104. this.index = index;
  34105. }
  34106. return IndexedVector2;
  34107. })(BABYLON.Vector2);
  34108. var PolygonPoints = (function () {
  34109. function PolygonPoints() {
  34110. this.elements = new Array();
  34111. }
  34112. PolygonPoints.prototype.add = function (originalPoints) {
  34113. var _this = this;
  34114. var result = new Array();
  34115. originalPoints.forEach(function (point) {
  34116. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  34117. var newPoint = new IndexedVector2(point, _this.elements.length);
  34118. result.push(newPoint);
  34119. _this.elements.push(newPoint);
  34120. }
  34121. });
  34122. return result;
  34123. };
  34124. PolygonPoints.prototype.computeBounds = function () {
  34125. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34126. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34127. this.elements.forEach(function (point) {
  34128. // x
  34129. if (point.x < lmin.x) {
  34130. lmin.x = point.x;
  34131. }
  34132. else if (point.x > lmax.x) {
  34133. lmax.x = point.x;
  34134. }
  34135. // y
  34136. if (point.y < lmin.y) {
  34137. lmin.y = point.y;
  34138. }
  34139. else if (point.y > lmax.y) {
  34140. lmax.y = point.y;
  34141. }
  34142. });
  34143. return {
  34144. min: lmin,
  34145. max: lmax,
  34146. width: lmax.x - lmin.x,
  34147. height: lmax.y - lmin.y
  34148. };
  34149. };
  34150. return PolygonPoints;
  34151. })();
  34152. var Polygon = (function () {
  34153. function Polygon() {
  34154. }
  34155. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  34156. return [
  34157. new BABYLON.Vector2(xmin, ymin),
  34158. new BABYLON.Vector2(xmax, ymin),
  34159. new BABYLON.Vector2(xmax, ymax),
  34160. new BABYLON.Vector2(xmin, ymax)
  34161. ];
  34162. };
  34163. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  34164. if (cx === void 0) { cx = 0; }
  34165. if (cy === void 0) { cy = 0; }
  34166. if (numberOfSides === void 0) { numberOfSides = 32; }
  34167. var result = new Array();
  34168. var angle = 0;
  34169. var increment = (Math.PI * 2) / numberOfSides;
  34170. for (var i = 0; i < numberOfSides; i++) {
  34171. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  34172. angle -= increment;
  34173. }
  34174. return result;
  34175. };
  34176. Polygon.Parse = function (input) {
  34177. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  34178. var i, result = [];
  34179. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  34180. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  34181. }
  34182. return result;
  34183. };
  34184. Polygon.StartingAt = function (x, y) {
  34185. return BABYLON.Path2.StartingAt(x, y);
  34186. };
  34187. return Polygon;
  34188. })();
  34189. BABYLON.Polygon = Polygon;
  34190. var PolygonMeshBuilder = (function () {
  34191. function PolygonMeshBuilder(name, contours, scene) {
  34192. this._points = new PolygonPoints();
  34193. this._outlinepoints = new PolygonPoints();
  34194. this._holes = [];
  34195. if (!("poly2tri" in window)) {
  34196. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  34197. }
  34198. this._name = name;
  34199. this._scene = scene;
  34200. var points;
  34201. if (contours instanceof BABYLON.Path2) {
  34202. points = contours.getPoints();
  34203. }
  34204. else {
  34205. points = contours;
  34206. }
  34207. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  34208. this._outlinepoints.add(points);
  34209. }
  34210. PolygonMeshBuilder.prototype.addHole = function (hole) {
  34211. this._swctx.addHole(this._points.add(hole));
  34212. var holepoints = new PolygonPoints();
  34213. holepoints.add(hole);
  34214. this._holes.push(holepoints);
  34215. return this;
  34216. };
  34217. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  34218. var _this = this;
  34219. if (updatable === void 0) { updatable = false; }
  34220. var result = new BABYLON.Mesh(this._name, this._scene);
  34221. var normals = [];
  34222. var positions = [];
  34223. var uvs = [];
  34224. var bounds = this._points.computeBounds();
  34225. this._points.elements.forEach(function (p) {
  34226. normals.push(0, 1.0, 0);
  34227. positions.push(p.x, 0, p.y);
  34228. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  34229. });
  34230. var indices = [];
  34231. this._swctx.triangulate();
  34232. this._swctx.getTriangles().forEach(function (triangle) {
  34233. triangle.getPoints().forEach(function (point) {
  34234. indices.push(point.index);
  34235. });
  34236. });
  34237. if (depth > 0) {
  34238. var positionscount = (positions.length / 3); //get the current pointcount
  34239. this._points.elements.forEach(function (p) {
  34240. normals.push(0, -1.0, 0);
  34241. positions.push(p.x, -depth, p.y);
  34242. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  34243. });
  34244. var p1; //we need to change order of point so the triangles are made in the rigth way.
  34245. var p2;
  34246. var poscounter = 0;
  34247. this._swctx.getTriangles().forEach(function (triangle) {
  34248. triangle.getPoints().forEach(function (point) {
  34249. switch (poscounter) {
  34250. case 0:
  34251. p1 = point;
  34252. break;
  34253. case 1:
  34254. p2 = point;
  34255. break;
  34256. case 2:
  34257. indices.push(point.index + positionscount);
  34258. indices.push(p2.index + positionscount);
  34259. indices.push(p1.index + positionscount);
  34260. poscounter = -1;
  34261. break;
  34262. }
  34263. poscounter++;
  34264. //indices.push((<IndexedVector2>point).index + positionscount);
  34265. });
  34266. });
  34267. //Add the sides
  34268. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  34269. this._holes.forEach(function (hole) {
  34270. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  34271. });
  34272. }
  34273. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  34274. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  34275. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  34276. result.setIndices(indices);
  34277. return result;
  34278. };
  34279. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  34280. var StartIndex = positions.length / 3;
  34281. var ulength = 0;
  34282. for (var i = 0; i < points.elements.length; i++) {
  34283. var p = points.elements[i];
  34284. var p1;
  34285. if ((i + 1) > points.elements.length - 1) {
  34286. p1 = points.elements[0];
  34287. }
  34288. else {
  34289. p1 = points.elements[i + 1];
  34290. }
  34291. positions.push(p.x, 0, p.y);
  34292. positions.push(p.x, -depth, p.y);
  34293. positions.push(p1.x, 0, p1.y);
  34294. positions.push(p1.x, -depth, p1.y);
  34295. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  34296. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  34297. var v3 = v2.subtract(v1);
  34298. var v4 = new BABYLON.Vector3(0, 1, 0);
  34299. var vn = BABYLON.Vector3.Cross(v3, v4);
  34300. vn = vn.normalize();
  34301. uvs.push(ulength / bounds.width, 0);
  34302. uvs.push(ulength / bounds.width, 1);
  34303. ulength += v3.length();
  34304. uvs.push((ulength / bounds.width), 0);
  34305. uvs.push((ulength / bounds.width), 1);
  34306. if (!flip) {
  34307. normals.push(-vn.x, -vn.y, -vn.z);
  34308. normals.push(-vn.x, -vn.y, -vn.z);
  34309. normals.push(-vn.x, -vn.y, -vn.z);
  34310. normals.push(-vn.x, -vn.y, -vn.z);
  34311. indices.push(StartIndex);
  34312. indices.push(StartIndex + 1);
  34313. indices.push(StartIndex + 2);
  34314. indices.push(StartIndex + 1);
  34315. indices.push(StartIndex + 3);
  34316. indices.push(StartIndex + 2);
  34317. }
  34318. else {
  34319. normals.push(vn.x, vn.y, vn.z);
  34320. normals.push(vn.x, vn.y, vn.z);
  34321. normals.push(vn.x, vn.y, vn.z);
  34322. normals.push(vn.x, vn.y, vn.z);
  34323. indices.push(StartIndex);
  34324. indices.push(StartIndex + 2);
  34325. indices.push(StartIndex + 1);
  34326. indices.push(StartIndex + 1);
  34327. indices.push(StartIndex + 2);
  34328. indices.push(StartIndex + 3);
  34329. }
  34330. StartIndex += 4;
  34331. }
  34332. ;
  34333. };
  34334. return PolygonMeshBuilder;
  34335. })();
  34336. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  34337. })(BABYLON || (BABYLON = {}));
  34338. var BABYLON;
  34339. (function (BABYLON) {
  34340. var Octree = (function () {
  34341. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  34342. if (maxDepth === void 0) { maxDepth = 2; }
  34343. this.maxDepth = maxDepth;
  34344. this.dynamicContent = new Array();
  34345. this._maxBlockCapacity = maxBlockCapacity || 64;
  34346. this._selectionContent = new BABYLON.SmartArray(1024);
  34347. this._creationFunc = creationFunc;
  34348. }
  34349. // Methods
  34350. Octree.prototype.update = function (worldMin, worldMax, entries) {
  34351. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  34352. };
  34353. Octree.prototype.addMesh = function (entry) {
  34354. for (var index = 0; index < this.blocks.length; index++) {
  34355. var block = this.blocks[index];
  34356. block.addEntry(entry);
  34357. }
  34358. };
  34359. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  34360. this._selectionContent.reset();
  34361. for (var index = 0; index < this.blocks.length; index++) {
  34362. var block = this.blocks[index];
  34363. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  34364. }
  34365. if (allowDuplicate) {
  34366. this._selectionContent.concat(this.dynamicContent);
  34367. }
  34368. else {
  34369. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34370. }
  34371. return this._selectionContent;
  34372. };
  34373. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  34374. this._selectionContent.reset();
  34375. for (var index = 0; index < this.blocks.length; index++) {
  34376. var block = this.blocks[index];
  34377. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  34378. }
  34379. if (allowDuplicate) {
  34380. this._selectionContent.concat(this.dynamicContent);
  34381. }
  34382. else {
  34383. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34384. }
  34385. return this._selectionContent;
  34386. };
  34387. Octree.prototype.intersectsRay = function (ray) {
  34388. this._selectionContent.reset();
  34389. for (var index = 0; index < this.blocks.length; index++) {
  34390. var block = this.blocks[index];
  34391. block.intersectsRay(ray, this._selectionContent);
  34392. }
  34393. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34394. return this._selectionContent;
  34395. };
  34396. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  34397. target.blocks = new Array();
  34398. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  34399. // Segmenting space
  34400. for (var x = 0; x < 2; x++) {
  34401. for (var y = 0; y < 2; y++) {
  34402. for (var z = 0; z < 2; z++) {
  34403. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  34404. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  34405. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  34406. block.addEntries(entries);
  34407. target.blocks.push(block);
  34408. }
  34409. }
  34410. }
  34411. };
  34412. Octree.CreationFuncForMeshes = function (entry, block) {
  34413. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34414. block.entries.push(entry);
  34415. }
  34416. };
  34417. Octree.CreationFuncForSubMeshes = function (entry, block) {
  34418. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34419. block.entries.push(entry);
  34420. }
  34421. };
  34422. return Octree;
  34423. })();
  34424. BABYLON.Octree = Octree;
  34425. })(BABYLON || (BABYLON = {}));
  34426. var BABYLON;
  34427. (function (BABYLON) {
  34428. var OctreeBlock = (function () {
  34429. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  34430. this.entries = new Array();
  34431. this._boundingVectors = new Array();
  34432. this._capacity = capacity;
  34433. this._depth = depth;
  34434. this._maxDepth = maxDepth;
  34435. this._creationFunc = creationFunc;
  34436. this._minPoint = minPoint;
  34437. this._maxPoint = maxPoint;
  34438. this._boundingVectors.push(minPoint.clone());
  34439. this._boundingVectors.push(maxPoint.clone());
  34440. this._boundingVectors.push(minPoint.clone());
  34441. this._boundingVectors[2].x = maxPoint.x;
  34442. this._boundingVectors.push(minPoint.clone());
  34443. this._boundingVectors[3].y = maxPoint.y;
  34444. this._boundingVectors.push(minPoint.clone());
  34445. this._boundingVectors[4].z = maxPoint.z;
  34446. this._boundingVectors.push(maxPoint.clone());
  34447. this._boundingVectors[5].z = minPoint.z;
  34448. this._boundingVectors.push(maxPoint.clone());
  34449. this._boundingVectors[6].x = minPoint.x;
  34450. this._boundingVectors.push(maxPoint.clone());
  34451. this._boundingVectors[7].y = minPoint.y;
  34452. }
  34453. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  34454. // Property
  34455. get: function () {
  34456. return this._capacity;
  34457. },
  34458. enumerable: true,
  34459. configurable: true
  34460. });
  34461. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  34462. get: function () {
  34463. return this._minPoint;
  34464. },
  34465. enumerable: true,
  34466. configurable: true
  34467. });
  34468. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  34469. get: function () {
  34470. return this._maxPoint;
  34471. },
  34472. enumerable: true,
  34473. configurable: true
  34474. });
  34475. // Methods
  34476. OctreeBlock.prototype.addEntry = function (entry) {
  34477. if (this.blocks) {
  34478. for (var index = 0; index < this.blocks.length; index++) {
  34479. var block = this.blocks[index];
  34480. block.addEntry(entry);
  34481. }
  34482. return;
  34483. }
  34484. this._creationFunc(entry, this);
  34485. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  34486. this.createInnerBlocks();
  34487. }
  34488. };
  34489. OctreeBlock.prototype.addEntries = function (entries) {
  34490. for (var index = 0; index < entries.length; index++) {
  34491. var mesh = entries[index];
  34492. this.addEntry(mesh);
  34493. }
  34494. };
  34495. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  34496. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  34497. if (this.blocks) {
  34498. for (var index = 0; index < this.blocks.length; index++) {
  34499. var block = this.blocks[index];
  34500. block.select(frustumPlanes, selection, allowDuplicate);
  34501. }
  34502. return;
  34503. }
  34504. if (allowDuplicate) {
  34505. selection.concat(this.entries);
  34506. }
  34507. else {
  34508. selection.concatWithNoDuplicate(this.entries);
  34509. }
  34510. }
  34511. };
  34512. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  34513. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  34514. if (this.blocks) {
  34515. for (var index = 0; index < this.blocks.length; index++) {
  34516. var block = this.blocks[index];
  34517. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  34518. }
  34519. return;
  34520. }
  34521. if (allowDuplicate) {
  34522. selection.concat(this.entries);
  34523. }
  34524. else {
  34525. selection.concatWithNoDuplicate(this.entries);
  34526. }
  34527. }
  34528. };
  34529. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  34530. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  34531. if (this.blocks) {
  34532. for (var index = 0; index < this.blocks.length; index++) {
  34533. var block = this.blocks[index];
  34534. block.intersectsRay(ray, selection);
  34535. }
  34536. return;
  34537. }
  34538. selection.concatWithNoDuplicate(this.entries);
  34539. }
  34540. };
  34541. OctreeBlock.prototype.createInnerBlocks = function () {
  34542. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  34543. };
  34544. return OctreeBlock;
  34545. })();
  34546. BABYLON.OctreeBlock = OctreeBlock;
  34547. })(BABYLON || (BABYLON = {}));
  34548. var BABYLON;
  34549. (function (BABYLON) {
  34550. var BlurPostProcess = (function (_super) {
  34551. __extends(BlurPostProcess, _super);
  34552. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  34553. var _this = this;
  34554. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34555. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  34556. this.direction = direction;
  34557. this.blurWidth = blurWidth;
  34558. this.onApply = function (effect) {
  34559. effect.setFloat2("screenSize", _this.width, _this.height);
  34560. effect.setVector2("direction", _this.direction);
  34561. effect.setFloat("blurWidth", _this.blurWidth);
  34562. };
  34563. }
  34564. return BlurPostProcess;
  34565. })(BABYLON.PostProcess);
  34566. BABYLON.BlurPostProcess = BlurPostProcess;
  34567. })(BABYLON || (BABYLON = {}));
  34568. var BABYLON;
  34569. (function (BABYLON) {
  34570. var RefractionPostProcess = (function (_super) {
  34571. __extends(RefractionPostProcess, _super);
  34572. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  34573. var _this = this;
  34574. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  34575. this.color = color;
  34576. this.depth = depth;
  34577. this.colorLevel = colorLevel;
  34578. this.onActivate = function (cam) {
  34579. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  34580. };
  34581. this.onApply = function (effect) {
  34582. effect.setColor3("baseColor", _this.color);
  34583. effect.setFloat("depth", _this.depth);
  34584. effect.setFloat("colorLevel", _this.colorLevel);
  34585. effect.setTexture("refractionSampler", _this._refRexture);
  34586. };
  34587. }
  34588. // Methods
  34589. RefractionPostProcess.prototype.dispose = function (camera) {
  34590. if (this._refRexture) {
  34591. this._refRexture.dispose();
  34592. }
  34593. _super.prototype.dispose.call(this, camera);
  34594. };
  34595. return RefractionPostProcess;
  34596. })(BABYLON.PostProcess);
  34597. BABYLON.RefractionPostProcess = RefractionPostProcess;
  34598. })(BABYLON || (BABYLON = {}));
  34599. var BABYLON;
  34600. (function (BABYLON) {
  34601. var BlackAndWhitePostProcess = (function (_super) {
  34602. __extends(BlackAndWhitePostProcess, _super);
  34603. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34604. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  34605. }
  34606. return BlackAndWhitePostProcess;
  34607. })(BABYLON.PostProcess);
  34608. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  34609. })(BABYLON || (BABYLON = {}));
  34610. var BABYLON;
  34611. (function (BABYLON) {
  34612. var ConvolutionPostProcess = (function (_super) {
  34613. __extends(ConvolutionPostProcess, _super);
  34614. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  34615. var _this = this;
  34616. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  34617. this.kernel = kernel;
  34618. this.onApply = function (effect) {
  34619. effect.setFloat2("screenSize", _this.width, _this.height);
  34620. effect.setArray("kernel", _this.kernel);
  34621. };
  34622. }
  34623. // Statics
  34624. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  34625. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  34626. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  34627. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  34628. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  34629. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  34630. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  34631. return ConvolutionPostProcess;
  34632. })(BABYLON.PostProcess);
  34633. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  34634. })(BABYLON || (BABYLON = {}));
  34635. var BABYLON;
  34636. (function (BABYLON) {
  34637. var FilterPostProcess = (function (_super) {
  34638. __extends(FilterPostProcess, _super);
  34639. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  34640. var _this = this;
  34641. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  34642. this.kernelMatrix = kernelMatrix;
  34643. this.onApply = function (effect) {
  34644. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  34645. };
  34646. }
  34647. return FilterPostProcess;
  34648. })(BABYLON.PostProcess);
  34649. BABYLON.FilterPostProcess = FilterPostProcess;
  34650. })(BABYLON || (BABYLON = {}));
  34651. var BABYLON;
  34652. (function (BABYLON) {
  34653. var FxaaPostProcess = (function (_super) {
  34654. __extends(FxaaPostProcess, _super);
  34655. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34656. var _this = this;
  34657. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  34658. this.onSizeChanged = function () {
  34659. _this.texelWidth = 1.0 / _this.width;
  34660. _this.texelHeight = 1.0 / _this.height;
  34661. };
  34662. this.onApply = function (effect) {
  34663. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  34664. };
  34665. }
  34666. return FxaaPostProcess;
  34667. })(BABYLON.PostProcess);
  34668. BABYLON.FxaaPostProcess = FxaaPostProcess;
  34669. })(BABYLON || (BABYLON = {}));
  34670. var BABYLON;
  34671. (function (BABYLON) {
  34672. var StereoscopicInterlacePostProcess = (function (_super) {
  34673. __extends(StereoscopicInterlacePostProcess, _super);
  34674. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  34675. var _this = this;
  34676. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  34677. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  34678. this.onSizeChanged = function () {
  34679. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  34680. };
  34681. this.onApply = function (effect) {
  34682. effect.setTextureFromPostProcess("camASampler", postProcessA);
  34683. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  34684. };
  34685. }
  34686. return StereoscopicInterlacePostProcess;
  34687. })(BABYLON.PostProcess);
  34688. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  34689. })(BABYLON || (BABYLON = {}));
  34690. var BABYLON;
  34691. (function (BABYLON) {
  34692. var LensFlare = (function () {
  34693. function LensFlare(size, position, color, imgUrl, system) {
  34694. this.size = size;
  34695. this.position = position;
  34696. this.dispose = function () {
  34697. if (this.texture) {
  34698. this.texture.dispose();
  34699. }
  34700. // Remove from scene
  34701. var index = this._system.lensFlares.indexOf(this);
  34702. this._system.lensFlares.splice(index, 1);
  34703. };
  34704. this.color = color || new BABYLON.Color3(1, 1, 1);
  34705. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  34706. this._system = system;
  34707. system.lensFlares.push(this);
  34708. }
  34709. return LensFlare;
  34710. })();
  34711. BABYLON.LensFlare = LensFlare;
  34712. })(BABYLON || (BABYLON = {}));
  34713. var BABYLON;
  34714. (function (BABYLON) {
  34715. var LensFlareSystem = (function () {
  34716. function LensFlareSystem(name, emitter, scene) {
  34717. this.name = name;
  34718. this.lensFlares = new Array();
  34719. this.borderLimit = 300;
  34720. this.layerMask = 0x0FFFFFFF;
  34721. this._vertexDeclaration = [2];
  34722. this._vertexStrideSize = 2 * 4;
  34723. this._isEnabled = true;
  34724. this._scene = scene;
  34725. this._emitter = emitter;
  34726. scene.lensFlareSystems.push(this);
  34727. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  34728. // VBO
  34729. var vertices = [];
  34730. vertices.push(1, 1);
  34731. vertices.push(-1, 1);
  34732. vertices.push(-1, -1);
  34733. vertices.push(1, -1);
  34734. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  34735. // Indices
  34736. var indices = [];
  34737. indices.push(0);
  34738. indices.push(1);
  34739. indices.push(2);
  34740. indices.push(0);
  34741. indices.push(2);
  34742. indices.push(3);
  34743. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34744. // Effects
  34745. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  34746. }
  34747. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  34748. get: function () {
  34749. return this._isEnabled;
  34750. },
  34751. set: function (value) {
  34752. this._isEnabled = value;
  34753. },
  34754. enumerable: true,
  34755. configurable: true
  34756. });
  34757. LensFlareSystem.prototype.getScene = function () {
  34758. return this._scene;
  34759. };
  34760. LensFlareSystem.prototype.getEmitter = function () {
  34761. return this._emitter;
  34762. };
  34763. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  34764. this._emitter = newEmitter;
  34765. };
  34766. LensFlareSystem.prototype.getEmitterPosition = function () {
  34767. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  34768. };
  34769. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  34770. var position = this.getEmitterPosition();
  34771. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  34772. this._positionX = position.x;
  34773. this._positionY = position.y;
  34774. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  34775. if (position.z > 0) {
  34776. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  34777. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  34778. return true;
  34779. }
  34780. }
  34781. return false;
  34782. };
  34783. LensFlareSystem.prototype._isVisible = function () {
  34784. if (!this._isEnabled) {
  34785. return false;
  34786. }
  34787. var emitterPosition = this.getEmitterPosition();
  34788. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  34789. var distance = direction.length();
  34790. direction.normalize();
  34791. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  34792. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  34793. return !pickInfo.hit || pickInfo.distance > distance;
  34794. };
  34795. LensFlareSystem.prototype.render = function () {
  34796. if (!this._effect.isReady())
  34797. return false;
  34798. var engine = this._scene.getEngine();
  34799. var viewport = this._scene.activeCamera.viewport;
  34800. var globalViewport = viewport.toScreenGlobal(engine);
  34801. // Position
  34802. if (!this.computeEffectivePosition(globalViewport)) {
  34803. return false;
  34804. }
  34805. // Visibility
  34806. if (!this._isVisible()) {
  34807. return false;
  34808. }
  34809. // Intensity
  34810. var awayX;
  34811. var awayY;
  34812. if (this._positionX < this.borderLimit + globalViewport.x) {
  34813. awayX = this.borderLimit + globalViewport.x - this._positionX;
  34814. }
  34815. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  34816. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  34817. }
  34818. else {
  34819. awayX = 0;
  34820. }
  34821. if (this._positionY < this.borderLimit + globalViewport.y) {
  34822. awayY = this.borderLimit + globalViewport.y - this._positionY;
  34823. }
  34824. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  34825. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  34826. }
  34827. else {
  34828. awayY = 0;
  34829. }
  34830. var away = (awayX > awayY) ? awayX : awayY;
  34831. if (away > this.borderLimit) {
  34832. away = this.borderLimit;
  34833. }
  34834. var intensity = 1.0 - (away / this.borderLimit);
  34835. if (intensity < 0) {
  34836. return false;
  34837. }
  34838. if (intensity > 1.0) {
  34839. intensity = 1.0;
  34840. }
  34841. // Position
  34842. var centerX = globalViewport.x + globalViewport.width / 2;
  34843. var centerY = globalViewport.y + globalViewport.height / 2;
  34844. var distX = centerX - this._positionX;
  34845. var distY = centerY - this._positionY;
  34846. // Effects
  34847. engine.enableEffect(this._effect);
  34848. engine.setState(false);
  34849. engine.setDepthBuffer(false);
  34850. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  34851. // VBOs
  34852. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  34853. // Flares
  34854. for (var index = 0; index < this.lensFlares.length; index++) {
  34855. var flare = this.lensFlares[index];
  34856. var x = centerX - (distX * flare.position);
  34857. var y = centerY - (distY * flare.position);
  34858. var cw = flare.size;
  34859. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  34860. var cx = 2 * (x / globalViewport.width) - 1.0;
  34861. var cy = 1.0 - 2 * (y / globalViewport.height);
  34862. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  34863. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  34864. // Texture
  34865. this._effect.setTexture("textureSampler", flare.texture);
  34866. // Color
  34867. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  34868. // Draw order
  34869. engine.draw(true, 0, 6);
  34870. }
  34871. engine.setDepthBuffer(true);
  34872. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34873. return true;
  34874. };
  34875. LensFlareSystem.prototype.dispose = function () {
  34876. if (this._vertexBuffer) {
  34877. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  34878. this._vertexBuffer = null;
  34879. }
  34880. if (this._indexBuffer) {
  34881. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34882. this._indexBuffer = null;
  34883. }
  34884. while (this.lensFlares.length) {
  34885. this.lensFlares[0].dispose();
  34886. }
  34887. // Remove from scene
  34888. var index = this._scene.lensFlareSystems.indexOf(this);
  34889. this._scene.lensFlareSystems.splice(index, 1);
  34890. };
  34891. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  34892. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  34893. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  34894. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  34895. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  34896. var parsedFlare = parsedLensFlareSystem.flares[index];
  34897. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  34898. }
  34899. return lensFlareSystem;
  34900. };
  34901. LensFlareSystem.prototype.serialize = function () {
  34902. var serializationObject = {};
  34903. serializationObject.emitterId = this.getEmitter().id;
  34904. serializationObject.borderLimit = this.borderLimit;
  34905. serializationObject.flares = [];
  34906. for (var index = 0; index < this.lensFlares.length; index++) {
  34907. var flare = this.lensFlares[index];
  34908. serializationObject.flares.push({
  34909. size: flare.size,
  34910. position: flare.position,
  34911. color: flare.color.asArray(),
  34912. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  34913. });
  34914. }
  34915. return serializationObject;
  34916. };
  34917. return LensFlareSystem;
  34918. })();
  34919. BABYLON.LensFlareSystem = LensFlareSystem;
  34920. })(BABYLON || (BABYLON = {}));
  34921. var BABYLON;
  34922. (function (BABYLON) {
  34923. // We're mainly based on the logic defined into the FreeCamera code
  34924. var DeviceOrientationCamera = (function (_super) {
  34925. __extends(DeviceOrientationCamera, _super);
  34926. function DeviceOrientationCamera(name, position, scene) {
  34927. var _this = this;
  34928. _super.call(this, name, position, scene);
  34929. this._offsetX = null;
  34930. this._offsetY = null;
  34931. this._orientationGamma = 0;
  34932. this._orientationBeta = 0;
  34933. this._initialOrientationGamma = 0;
  34934. this._initialOrientationBeta = 0;
  34935. this.angularSensibility = 10000.0;
  34936. this.moveSensibility = 50.0;
  34937. window.addEventListener("resize", function () {
  34938. _this._initialOrientationGamma = null;
  34939. }, false);
  34940. }
  34941. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  34942. var _this = this;
  34943. if (this._attachedCanvas) {
  34944. return;
  34945. }
  34946. this._attachedCanvas = canvas;
  34947. if (!this._orientationChanged) {
  34948. this._orientationChanged = function (evt) {
  34949. if (!_this._initialOrientationGamma) {
  34950. _this._initialOrientationGamma = evt.gamma;
  34951. _this._initialOrientationBeta = evt.beta;
  34952. }
  34953. _this._orientationGamma = evt.gamma;
  34954. _this._orientationBeta = evt.beta;
  34955. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  34956. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  34957. };
  34958. }
  34959. window.addEventListener("deviceorientation", this._orientationChanged);
  34960. };
  34961. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  34962. if (this._attachedCanvas !== canvas) {
  34963. return;
  34964. }
  34965. window.removeEventListener("deviceorientation", this._orientationChanged);
  34966. this._attachedCanvas = null;
  34967. this._orientationGamma = 0;
  34968. this._orientationBeta = 0;
  34969. this._initialOrientationGamma = 0;
  34970. this._initialOrientationBeta = 0;
  34971. };
  34972. DeviceOrientationCamera.prototype._checkInputs = function () {
  34973. if (!this._offsetX) {
  34974. return;
  34975. }
  34976. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  34977. var speed = this._computeLocalCameraSpeed();
  34978. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  34979. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  34980. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  34981. _super.prototype._checkInputs.call(this);
  34982. };
  34983. DeviceOrientationCamera.prototype.getTypeName = function () {
  34984. return "DeviceOrientationCamera";
  34985. };
  34986. __decorate([
  34987. BABYLON.serialize()
  34988. ], DeviceOrientationCamera.prototype, "angularSensibility", void 0);
  34989. __decorate([
  34990. BABYLON.serialize()
  34991. ], DeviceOrientationCamera.prototype, "moveSensibility", void 0);
  34992. return DeviceOrientationCamera;
  34993. })(BABYLON.FreeCamera);
  34994. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  34995. })(BABYLON || (BABYLON = {}));
  34996. var BABYLON;
  34997. (function (BABYLON) {
  34998. var Analyser = (function () {
  34999. function Analyser(scene) {
  35000. this.SMOOTHING = 0.75;
  35001. this.FFT_SIZE = 512;
  35002. this.BARGRAPHAMPLITUDE = 256;
  35003. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  35004. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  35005. this._scene = scene;
  35006. this._audioEngine = BABYLON.Engine.audioEngine;
  35007. if (this._audioEngine.canUseWebAudio) {
  35008. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  35009. this._webAudioAnalyser.minDecibels = -140;
  35010. this._webAudioAnalyser.maxDecibels = 0;
  35011. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35012. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35013. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  35014. }
  35015. }
  35016. Analyser.prototype.getFrequencyBinCount = function () {
  35017. if (this._audioEngine.canUseWebAudio) {
  35018. return this._webAudioAnalyser.frequencyBinCount;
  35019. }
  35020. else {
  35021. return 0;
  35022. }
  35023. };
  35024. Analyser.prototype.getByteFrequencyData = function () {
  35025. if (this._audioEngine.canUseWebAudio) {
  35026. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35027. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35028. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  35029. }
  35030. return this._byteFreqs;
  35031. };
  35032. Analyser.prototype.getByteTimeDomainData = function () {
  35033. if (this._audioEngine.canUseWebAudio) {
  35034. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35035. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35036. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  35037. }
  35038. return this._byteTime;
  35039. };
  35040. Analyser.prototype.getFloatFrequencyData = function () {
  35041. if (this._audioEngine.canUseWebAudio) {
  35042. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35043. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35044. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  35045. }
  35046. return this._floatFreqs;
  35047. };
  35048. Analyser.prototype.drawDebugCanvas = function () {
  35049. var _this = this;
  35050. if (this._audioEngine.canUseWebAudio) {
  35051. if (!this._debugCanvas) {
  35052. this._debugCanvas = document.createElement("canvas");
  35053. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  35054. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  35055. this._debugCanvas.style.position = "absolute";
  35056. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  35057. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  35058. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  35059. document.body.appendChild(this._debugCanvas);
  35060. this._registerFunc = function () {
  35061. _this.drawDebugCanvas();
  35062. };
  35063. this._scene.registerBeforeRender(this._registerFunc);
  35064. }
  35065. if (this._registerFunc) {
  35066. var workingArray = this.getByteFrequencyData();
  35067. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  35068. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  35069. // Draw the frequency domain chart.
  35070. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  35071. var value = workingArray[i];
  35072. var percent = value / this.BARGRAPHAMPLITUDE;
  35073. var height = this.DEBUGCANVASSIZE.height * percent;
  35074. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  35075. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  35076. var hue = i / this.getFrequencyBinCount() * 360;
  35077. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  35078. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  35079. }
  35080. }
  35081. }
  35082. };
  35083. Analyser.prototype.stopDebugCanvas = function () {
  35084. if (this._debugCanvas) {
  35085. this._scene.unregisterBeforeRender(this._registerFunc);
  35086. this._registerFunc = null;
  35087. document.body.removeChild(this._debugCanvas);
  35088. this._debugCanvas = null;
  35089. this._debugCanvasContext = null;
  35090. }
  35091. };
  35092. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  35093. if (this._audioEngine.canUseWebAudio) {
  35094. inputAudioNode.connect(this._webAudioAnalyser);
  35095. this._webAudioAnalyser.connect(outputAudioNode);
  35096. }
  35097. };
  35098. Analyser.prototype.dispose = function () {
  35099. if (this._audioEngine.canUseWebAudio) {
  35100. this._webAudioAnalyser.disconnect();
  35101. }
  35102. };
  35103. return Analyser;
  35104. })();
  35105. BABYLON.Analyser = Analyser;
  35106. })(BABYLON || (BABYLON = {}));
  35107. var BABYLON;
  35108. (function (BABYLON) {
  35109. var AudioEngine = (function () {
  35110. function AudioEngine() {
  35111. this._audioContext = null;
  35112. this._audioContextInitialized = false;
  35113. this.canUseWebAudio = false;
  35114. this.WarnedWebAudioUnsupported = false;
  35115. this.unlocked = false;
  35116. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35117. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35118. this.canUseWebAudio = true;
  35119. }
  35120. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35121. this._unlockiOSaudio();
  35122. }
  35123. else {
  35124. this.unlocked = true;
  35125. }
  35126. }
  35127. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35128. get: function () {
  35129. if (!this._audioContextInitialized) {
  35130. this._initializeAudioContext();
  35131. }
  35132. return this._audioContext;
  35133. },
  35134. enumerable: true,
  35135. configurable: true
  35136. });
  35137. AudioEngine.prototype._unlockiOSaudio = function () {
  35138. var _this = this;
  35139. var unlockaudio = function () {
  35140. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35141. var source = _this.audioContext.createBufferSource();
  35142. source.buffer = buffer;
  35143. source.connect(_this.audioContext.destination);
  35144. source.start(0);
  35145. setTimeout(function () {
  35146. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35147. _this.unlocked = true;
  35148. window.removeEventListener('touchend', unlockaudio, false);
  35149. if (_this.onAudioUnlocked) {
  35150. _this.onAudioUnlocked();
  35151. }
  35152. }
  35153. }, 0);
  35154. };
  35155. window.addEventListener('touchend', unlockaudio, false);
  35156. };
  35157. AudioEngine.prototype._initializeAudioContext = function () {
  35158. try {
  35159. if (this.canUseWebAudio) {
  35160. this._audioContext = new AudioContext();
  35161. // create a global volume gain node
  35162. this.masterGain = this._audioContext.createGain();
  35163. this.masterGain.gain.value = 1;
  35164. this.masterGain.connect(this._audioContext.destination);
  35165. this._audioContextInitialized = true;
  35166. }
  35167. }
  35168. catch (e) {
  35169. this.canUseWebAudio = false;
  35170. BABYLON.Tools.Error("Web Audio: " + e.message);
  35171. }
  35172. };
  35173. AudioEngine.prototype.dispose = function () {
  35174. if (this.canUseWebAudio && this._audioContextInitialized) {
  35175. if (this._connectedAnalyser) {
  35176. this._connectedAnalyser.stopDebugCanvas();
  35177. this._connectedAnalyser.dispose();
  35178. this.masterGain.disconnect();
  35179. this.masterGain.connect(this._audioContext.destination);
  35180. this._connectedAnalyser = null;
  35181. }
  35182. this.masterGain.gain.value = 1;
  35183. }
  35184. this.WarnedWebAudioUnsupported = false;
  35185. };
  35186. AudioEngine.prototype.getGlobalVolume = function () {
  35187. if (this.canUseWebAudio && this._audioContextInitialized) {
  35188. return this.masterGain.gain.value;
  35189. }
  35190. else {
  35191. return -1;
  35192. }
  35193. };
  35194. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35195. if (this.canUseWebAudio && this._audioContextInitialized) {
  35196. this.masterGain.gain.value = newVolume;
  35197. }
  35198. };
  35199. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35200. if (this._connectedAnalyser) {
  35201. this._connectedAnalyser.stopDebugCanvas();
  35202. }
  35203. if (this.canUseWebAudio && this._audioContextInitialized) {
  35204. this._connectedAnalyser = analyser;
  35205. this.masterGain.disconnect();
  35206. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35207. }
  35208. };
  35209. return AudioEngine;
  35210. })();
  35211. BABYLON.AudioEngine = AudioEngine;
  35212. })(BABYLON || (BABYLON = {}));
  35213. var BABYLON;
  35214. (function (BABYLON) {
  35215. var Sound = (function () {
  35216. /**
  35217. * Create a sound and attach it to a scene
  35218. * @param name Name of your sound
  35219. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35220. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35221. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35222. */
  35223. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35224. var _this = this;
  35225. this.autoplay = false;
  35226. this.loop = false;
  35227. this.useCustomAttenuation = false;
  35228. this.spatialSound = false;
  35229. this.refDistance = 1;
  35230. this.rolloffFactor = 1;
  35231. this.maxDistance = 100;
  35232. this.distanceModel = "linear";
  35233. this._panningModel = "equalpower";
  35234. this._playbackRate = 1;
  35235. this._streaming = false;
  35236. this._startTime = 0;
  35237. this._startOffset = 0;
  35238. this._position = BABYLON.Vector3.Zero();
  35239. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35240. this._volume = 1;
  35241. this._isLoaded = false;
  35242. this._isReadyToPlay = false;
  35243. this.isPlaying = false;
  35244. this.isPaused = false;
  35245. this._isDirectional = false;
  35246. // Used if you'd like to create a directional sound.
  35247. // If not set, the sound will be omnidirectional
  35248. this._coneInnerAngle = 360;
  35249. this._coneOuterAngle = 360;
  35250. this._coneOuterGain = 0;
  35251. this._isOutputConnected = false;
  35252. this.name = name;
  35253. this._scene = scene;
  35254. this._readyToPlayCallback = readyToPlayCallback;
  35255. // Default custom attenuation function is a linear attenuation
  35256. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35257. if (currentDistance < maxDistance) {
  35258. return currentVolume * (1 - currentDistance / maxDistance);
  35259. }
  35260. else {
  35261. return 0;
  35262. }
  35263. };
  35264. if (options) {
  35265. this.autoplay = options.autoplay || false;
  35266. this.loop = options.loop || false;
  35267. // if volume === 0, we need another way to check this option
  35268. if (options.volume !== undefined) {
  35269. this._volume = options.volume;
  35270. }
  35271. this.spatialSound = options.spatialSound || false;
  35272. this.maxDistance = options.maxDistance || 100;
  35273. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35274. this.rolloffFactor = options.rolloffFactor || 1;
  35275. this.refDistance = options.refDistance || 1;
  35276. this.distanceModel = options.distanceModel || "linear";
  35277. this._playbackRate = options.playbackRate || 1;
  35278. this._streaming = options.streaming || false;
  35279. }
  35280. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35281. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35282. this._soundGain.gain.value = this._volume;
  35283. this._inputAudioNode = this._soundGain;
  35284. this._ouputAudioNode = this._soundGain;
  35285. if (this.spatialSound) {
  35286. this._createSpatialParameters();
  35287. }
  35288. this._scene.mainSoundTrack.AddSound(this);
  35289. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35290. if (urlOrArrayBuffer) {
  35291. // If it's an URL
  35292. if (typeof (urlOrArrayBuffer) === "string") {
  35293. // Loading sound using XHR2
  35294. if (!this._streaming) {
  35295. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35296. }
  35297. else {
  35298. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35299. this._htmlAudioElement.controls = false;
  35300. this._htmlAudioElement.loop = this.loop;
  35301. this._htmlAudioElement.crossOrigin = "anonymous";
  35302. this._htmlAudioElement.preload = "auto";
  35303. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35304. _this._isReadyToPlay = true;
  35305. if (_this.autoplay) {
  35306. _this.play();
  35307. }
  35308. if (_this._readyToPlayCallback) {
  35309. _this._readyToPlayCallback();
  35310. }
  35311. });
  35312. document.body.appendChild(this._htmlAudioElement);
  35313. }
  35314. }
  35315. else {
  35316. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35317. if (urlOrArrayBuffer.byteLength > 0) {
  35318. this._soundLoaded(urlOrArrayBuffer);
  35319. }
  35320. }
  35321. else {
  35322. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35323. }
  35324. }
  35325. }
  35326. }
  35327. else {
  35328. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35329. this._scene.mainSoundTrack.AddSound(this);
  35330. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35331. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35332. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35333. }
  35334. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35335. if (this._readyToPlayCallback) {
  35336. window.setTimeout(function () {
  35337. _this._readyToPlayCallback();
  35338. }, 1000);
  35339. }
  35340. }
  35341. }
  35342. Sound.prototype.dispose = function () {
  35343. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35344. if (this.isPlaying) {
  35345. this.stop();
  35346. }
  35347. this._isReadyToPlay = false;
  35348. if (this.soundTrackId === -1) {
  35349. this._scene.mainSoundTrack.RemoveSound(this);
  35350. }
  35351. else {
  35352. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35353. }
  35354. if (this._soundGain) {
  35355. this._soundGain.disconnect();
  35356. this._soundGain = null;
  35357. }
  35358. if (this._soundPanner) {
  35359. this._soundPanner.disconnect();
  35360. this._soundPanner = null;
  35361. }
  35362. if (this._soundSource) {
  35363. this._soundSource.disconnect();
  35364. this._soundSource = null;
  35365. }
  35366. this._audioBuffer = null;
  35367. if (this._htmlAudioElement) {
  35368. this._htmlAudioElement.pause();
  35369. this._htmlAudioElement.src = "";
  35370. document.body.removeChild(this._htmlAudioElement);
  35371. }
  35372. if (this._connectedMesh) {
  35373. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35374. this._connectedMesh = null;
  35375. }
  35376. }
  35377. };
  35378. Sound.prototype._soundLoaded = function (audioData) {
  35379. var _this = this;
  35380. this._isLoaded = true;
  35381. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35382. _this._audioBuffer = buffer;
  35383. _this._isReadyToPlay = true;
  35384. if (_this.autoplay) {
  35385. _this.play();
  35386. }
  35387. if (_this._readyToPlayCallback) {
  35388. _this._readyToPlayCallback();
  35389. }
  35390. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35391. };
  35392. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35393. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35394. this._audioBuffer = audioBuffer;
  35395. this._isReadyToPlay = true;
  35396. }
  35397. };
  35398. Sound.prototype.updateOptions = function (options) {
  35399. if (options) {
  35400. this.loop = options.loop || this.loop;
  35401. this.maxDistance = options.maxDistance || this.maxDistance;
  35402. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35403. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35404. this.refDistance = options.refDistance || this.refDistance;
  35405. this.distanceModel = options.distanceModel || this.distanceModel;
  35406. this._playbackRate = options.playbackRate || this._playbackRate;
  35407. this._updateSpatialParameters();
  35408. if (this.isPlaying) {
  35409. if (this._streaming) {
  35410. this._htmlAudioElement.playbackRate = this._playbackRate;
  35411. }
  35412. else {
  35413. this._soundSource.playbackRate.value = this._playbackRate;
  35414. }
  35415. }
  35416. }
  35417. };
  35418. Sound.prototype._createSpatialParameters = function () {
  35419. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35420. if (this._scene.headphone) {
  35421. this._panningModel = "HRTF";
  35422. }
  35423. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35424. this._updateSpatialParameters();
  35425. this._soundPanner.connect(this._ouputAudioNode);
  35426. this._inputAudioNode = this._soundPanner;
  35427. }
  35428. };
  35429. Sound.prototype._updateSpatialParameters = function () {
  35430. if (this.spatialSound) {
  35431. if (this.useCustomAttenuation) {
  35432. // Tricks to disable in a way embedded Web Audio attenuation
  35433. this._soundPanner.distanceModel = "linear";
  35434. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35435. this._soundPanner.refDistance = 1;
  35436. this._soundPanner.rolloffFactor = 1;
  35437. this._soundPanner.panningModel = this._panningModel;
  35438. }
  35439. else {
  35440. this._soundPanner.distanceModel = this.distanceModel;
  35441. this._soundPanner.maxDistance = this.maxDistance;
  35442. this._soundPanner.refDistance = this.refDistance;
  35443. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35444. this._soundPanner.panningModel = this._panningModel;
  35445. }
  35446. }
  35447. };
  35448. Sound.prototype.switchPanningModelToHRTF = function () {
  35449. this._panningModel = "HRTF";
  35450. this._switchPanningModel();
  35451. };
  35452. Sound.prototype.switchPanningModelToEqualPower = function () {
  35453. this._panningModel = "equalpower";
  35454. this._switchPanningModel();
  35455. };
  35456. Sound.prototype._switchPanningModel = function () {
  35457. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35458. this._soundPanner.panningModel = this._panningModel;
  35459. }
  35460. };
  35461. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35462. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35463. if (this._isOutputConnected) {
  35464. this._ouputAudioNode.disconnect();
  35465. }
  35466. this._ouputAudioNode.connect(soundTrackAudioNode);
  35467. this._isOutputConnected = true;
  35468. }
  35469. };
  35470. /**
  35471. * Transform this sound into a directional source
  35472. * @param coneInnerAngle Size of the inner cone in degree
  35473. * @param coneOuterAngle Size of the outer cone in degree
  35474. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35475. */
  35476. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35477. if (coneOuterAngle < coneInnerAngle) {
  35478. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35479. return;
  35480. }
  35481. this._coneInnerAngle = coneInnerAngle;
  35482. this._coneOuterAngle = coneOuterAngle;
  35483. this._coneOuterGain = coneOuterGain;
  35484. this._isDirectional = true;
  35485. if (this.isPlaying && this.loop) {
  35486. this.stop();
  35487. this.play();
  35488. }
  35489. };
  35490. Sound.prototype.setPosition = function (newPosition) {
  35491. this._position = newPosition;
  35492. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35493. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35494. }
  35495. };
  35496. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35497. this._localDirection = newLocalDirection;
  35498. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35499. this._updateDirection();
  35500. }
  35501. };
  35502. Sound.prototype._updateDirection = function () {
  35503. var mat = this._connectedMesh.getWorldMatrix();
  35504. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35505. direction.normalize();
  35506. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35507. };
  35508. Sound.prototype.updateDistanceFromListener = function () {
  35509. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35510. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35511. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35512. }
  35513. };
  35514. Sound.prototype.setAttenuationFunction = function (callback) {
  35515. this._customAttenuationFunction = callback;
  35516. };
  35517. /**
  35518. * Play the sound
  35519. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35520. */
  35521. Sound.prototype.play = function (time) {
  35522. var _this = this;
  35523. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35524. try {
  35525. if (this._startOffset < 0) {
  35526. time = -this._startOffset;
  35527. this._startOffset = 0;
  35528. }
  35529. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35530. if (!this._soundSource || !this._streamingSource) {
  35531. if (this.spatialSound) {
  35532. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35533. if (this._isDirectional) {
  35534. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35535. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35536. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35537. if (this._connectedMesh) {
  35538. this._updateDirection();
  35539. }
  35540. else {
  35541. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35542. }
  35543. }
  35544. }
  35545. }
  35546. if (this._streaming) {
  35547. if (!this._streamingSource) {
  35548. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35549. this._htmlAudioElement.onended = function () { _this._onended(); };
  35550. this._htmlAudioElement.playbackRate = this._playbackRate;
  35551. }
  35552. this._streamingSource.disconnect();
  35553. this._streamingSource.connect(this._inputAudioNode);
  35554. this._htmlAudioElement.play();
  35555. }
  35556. else {
  35557. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35558. this._soundSource.buffer = this._audioBuffer;
  35559. this._soundSource.connect(this._inputAudioNode);
  35560. this._soundSource.loop = this.loop;
  35561. this._soundSource.playbackRate.value = this._playbackRate;
  35562. this._soundSource.onended = function () { _this._onended(); };
  35563. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  35564. }
  35565. this._startTime = startTime;
  35566. this.isPlaying = true;
  35567. this.isPaused = false;
  35568. }
  35569. catch (ex) {
  35570. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35571. }
  35572. }
  35573. };
  35574. Sound.prototype._onended = function () {
  35575. this.isPlaying = false;
  35576. if (this.onended) {
  35577. this.onended();
  35578. }
  35579. };
  35580. /**
  35581. * Stop the sound
  35582. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35583. */
  35584. Sound.prototype.stop = function (time) {
  35585. if (this.isPlaying) {
  35586. if (this._streaming) {
  35587. this._htmlAudioElement.pause();
  35588. // Test needed for Firefox or it will generate an Invalid State Error
  35589. if (this._htmlAudioElement.currentTime > 0) {
  35590. this._htmlAudioElement.currentTime = 0;
  35591. }
  35592. }
  35593. else {
  35594. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35595. this._soundSource.stop(stopTime);
  35596. if (!this.isPaused) {
  35597. this._startOffset = 0;
  35598. }
  35599. }
  35600. this.isPlaying = false;
  35601. }
  35602. };
  35603. Sound.prototype.pause = function () {
  35604. if (this.isPlaying) {
  35605. this.isPaused = true;
  35606. if (this._streaming) {
  35607. this._htmlAudioElement.pause();
  35608. }
  35609. else {
  35610. this.stop(0);
  35611. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35612. }
  35613. }
  35614. };
  35615. Sound.prototype.setVolume = function (newVolume, time) {
  35616. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35617. if (time) {
  35618. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35619. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35620. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35621. }
  35622. else {
  35623. this._soundGain.gain.value = newVolume;
  35624. }
  35625. }
  35626. this._volume = newVolume;
  35627. };
  35628. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35629. this._playbackRate = newPlaybackRate;
  35630. if (this.isPlaying) {
  35631. if (this._streaming) {
  35632. this._htmlAudioElement.playbackRate = this._playbackRate;
  35633. }
  35634. else {
  35635. this._soundSource.playbackRate.value = this._playbackRate;
  35636. }
  35637. }
  35638. };
  35639. Sound.prototype.getVolume = function () {
  35640. return this._volume;
  35641. };
  35642. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35643. var _this = this;
  35644. if (this._connectedMesh) {
  35645. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35646. this._registerFunc = null;
  35647. }
  35648. this._connectedMesh = meshToConnectTo;
  35649. if (!this.spatialSound) {
  35650. this.spatialSound = true;
  35651. this._createSpatialParameters();
  35652. if (this.isPlaying && this.loop) {
  35653. this.stop();
  35654. this.play();
  35655. }
  35656. }
  35657. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35658. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35659. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35660. };
  35661. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35662. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35663. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35664. this._updateDirection();
  35665. }
  35666. };
  35667. Sound.prototype.clone = function () {
  35668. var _this = this;
  35669. if (!this._streaming) {
  35670. var setBufferAndRun = function () {
  35671. if (_this._isReadyToPlay) {
  35672. clonedSound._audioBuffer = _this.getAudioBuffer();
  35673. clonedSound._isReadyToPlay = true;
  35674. if (clonedSound.autoplay) {
  35675. clonedSound.play();
  35676. }
  35677. }
  35678. else {
  35679. window.setTimeout(setBufferAndRun, 300);
  35680. }
  35681. };
  35682. var currentOptions = {
  35683. autoplay: this.autoplay, loop: this.loop,
  35684. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35685. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35686. refDistance: this.refDistance, distanceModel: this.distanceModel
  35687. };
  35688. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35689. if (this.useCustomAttenuation) {
  35690. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35691. }
  35692. clonedSound.setPosition(this._position);
  35693. clonedSound.setPlaybackRate(this._playbackRate);
  35694. setBufferAndRun();
  35695. return clonedSound;
  35696. }
  35697. else {
  35698. return null;
  35699. }
  35700. };
  35701. Sound.prototype.getAudioBuffer = function () {
  35702. return this._audioBuffer;
  35703. };
  35704. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35705. var soundName = parsedSound.name;
  35706. var soundUrl;
  35707. if (parsedSound.url) {
  35708. soundUrl = rootUrl + parsedSound.url;
  35709. }
  35710. else {
  35711. soundUrl = rootUrl + soundName;
  35712. }
  35713. var options = {
  35714. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35715. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35716. rolloffFactor: parsedSound.rolloffFactor,
  35717. refDistance: parsedSound.refDistance,
  35718. distanceModel: parsedSound.distanceModel,
  35719. playbackRate: parsedSound.playbackRate
  35720. };
  35721. var newSound;
  35722. if (!sourceSound) {
  35723. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35724. scene._addPendingData(newSound);
  35725. }
  35726. else {
  35727. var setBufferAndRun = function () {
  35728. if (sourceSound._isReadyToPlay) {
  35729. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35730. newSound._isReadyToPlay = true;
  35731. if (newSound.autoplay) {
  35732. newSound.play();
  35733. }
  35734. }
  35735. else {
  35736. window.setTimeout(setBufferAndRun, 300);
  35737. }
  35738. };
  35739. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35740. setBufferAndRun();
  35741. }
  35742. if (parsedSound.position) {
  35743. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35744. newSound.setPosition(soundPosition);
  35745. }
  35746. if (parsedSound.isDirectional) {
  35747. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35748. if (parsedSound.localDirectionToMesh) {
  35749. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35750. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35751. }
  35752. }
  35753. if (parsedSound.connectedMeshId) {
  35754. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35755. if (connectedMesh) {
  35756. newSound.attachToMesh(connectedMesh);
  35757. }
  35758. }
  35759. return newSound;
  35760. };
  35761. return Sound;
  35762. })();
  35763. BABYLON.Sound = Sound;
  35764. })(BABYLON || (BABYLON = {}));
  35765. var BABYLON;
  35766. (function (BABYLON) {
  35767. var SoundTrack = (function () {
  35768. function SoundTrack(scene, options) {
  35769. this.id = -1;
  35770. this._isMainTrack = false;
  35771. this._isInitialized = false;
  35772. this._scene = scene;
  35773. this.soundCollection = new Array();
  35774. this._options = options;
  35775. if (!this._isMainTrack) {
  35776. this._scene.soundTracks.push(this);
  35777. this.id = this._scene.soundTracks.length - 1;
  35778. }
  35779. }
  35780. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35781. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35782. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35783. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35784. if (this._options) {
  35785. if (this._options.volume) {
  35786. this._outputAudioNode.gain.value = this._options.volume;
  35787. }
  35788. if (this._options.mainTrack) {
  35789. this._isMainTrack = this._options.mainTrack;
  35790. }
  35791. }
  35792. this._isInitialized = true;
  35793. }
  35794. };
  35795. SoundTrack.prototype.dispose = function () {
  35796. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35797. if (this._connectedAnalyser) {
  35798. this._connectedAnalyser.stopDebugCanvas();
  35799. }
  35800. while (this.soundCollection.length) {
  35801. this.soundCollection[0].dispose();
  35802. }
  35803. if (this._outputAudioNode) {
  35804. this._outputAudioNode.disconnect();
  35805. }
  35806. this._outputAudioNode = null;
  35807. }
  35808. };
  35809. SoundTrack.prototype.AddSound = function (sound) {
  35810. if (!this._isInitialized) {
  35811. this._initializeSoundTrackAudioGraph();
  35812. }
  35813. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35814. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35815. }
  35816. if (sound.soundTrackId) {
  35817. if (sound.soundTrackId === -1) {
  35818. this._scene.mainSoundTrack.RemoveSound(sound);
  35819. }
  35820. else {
  35821. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35822. }
  35823. }
  35824. this.soundCollection.push(sound);
  35825. sound.soundTrackId = this.id;
  35826. };
  35827. SoundTrack.prototype.RemoveSound = function (sound) {
  35828. var index = this.soundCollection.indexOf(sound);
  35829. if (index !== -1) {
  35830. this.soundCollection.splice(index, 1);
  35831. }
  35832. };
  35833. SoundTrack.prototype.setVolume = function (newVolume) {
  35834. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35835. this._outputAudioNode.gain.value = newVolume;
  35836. }
  35837. };
  35838. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35839. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35840. for (var i = 0; i < this.soundCollection.length; i++) {
  35841. this.soundCollection[i].switchPanningModelToHRTF();
  35842. }
  35843. }
  35844. };
  35845. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35846. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35847. for (var i = 0; i < this.soundCollection.length; i++) {
  35848. this.soundCollection[i].switchPanningModelToEqualPower();
  35849. }
  35850. }
  35851. };
  35852. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35853. if (this._connectedAnalyser) {
  35854. this._connectedAnalyser.stopDebugCanvas();
  35855. }
  35856. this._connectedAnalyser = analyser;
  35857. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35858. this._outputAudioNode.disconnect();
  35859. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35860. }
  35861. };
  35862. return SoundTrack;
  35863. })();
  35864. BABYLON.SoundTrack = SoundTrack;
  35865. })(BABYLON || (BABYLON = {}));
  35866. var BABYLON;
  35867. (function (BABYLON) {
  35868. var DepthRenderer = (function () {
  35869. function DepthRenderer(scene, type) {
  35870. var _this = this;
  35871. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  35872. this._viewMatrix = BABYLON.Matrix.Zero();
  35873. this._projectionMatrix = BABYLON.Matrix.Zero();
  35874. this._transformMatrix = BABYLON.Matrix.Zero();
  35875. this._worldViewProjection = BABYLON.Matrix.Zero();
  35876. this._scene = scene;
  35877. var engine = scene.getEngine();
  35878. // Render target
  35879. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  35880. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35881. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35882. this._depthMap.refreshRate = 1;
  35883. this._depthMap.renderParticles = false;
  35884. this._depthMap.renderList = null;
  35885. // set default depth value to 1.0 (far away)
  35886. this._depthMap.onClear = function (engine) {
  35887. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  35888. };
  35889. // Custom render function
  35890. var renderSubMesh = function (subMesh) {
  35891. var mesh = subMesh.getRenderingMesh();
  35892. var scene = _this._scene;
  35893. var engine = scene.getEngine();
  35894. // Culling
  35895. engine.setState(subMesh.getMaterial().backFaceCulling);
  35896. // Managing instances
  35897. var batch = mesh._getInstancesRenderList(subMesh._id);
  35898. if (batch.mustReturn) {
  35899. return;
  35900. }
  35901. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35902. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35903. engine.enableEffect(_this._effect);
  35904. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  35905. var material = subMesh.getMaterial();
  35906. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35907. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  35908. // Alpha test
  35909. if (material && material.needAlphaTesting()) {
  35910. var alphaTexture = material.getAlphaTestTexture();
  35911. _this._effect.setTexture("diffuseSampler", alphaTexture);
  35912. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35913. }
  35914. // Bones
  35915. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35916. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35917. }
  35918. // Draw
  35919. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35920. }
  35921. };
  35922. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  35923. var index;
  35924. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35925. renderSubMesh(opaqueSubMeshes.data[index]);
  35926. }
  35927. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35928. renderSubMesh(alphaTestSubMeshes.data[index]);
  35929. }
  35930. };
  35931. }
  35932. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  35933. var defines = [];
  35934. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35935. var mesh = subMesh.getMesh();
  35936. var scene = mesh.getScene();
  35937. var material = subMesh.getMaterial();
  35938. // Alpha test
  35939. if (material && material.needAlphaTesting()) {
  35940. defines.push("#define ALPHATEST");
  35941. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35942. attribs.push(BABYLON.VertexBuffer.UVKind);
  35943. defines.push("#define UV1");
  35944. }
  35945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35946. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35947. defines.push("#define UV2");
  35948. }
  35949. }
  35950. // Bones
  35951. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35954. if (mesh.numBoneInfluencers > 4) {
  35955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35957. }
  35958. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35959. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35960. }
  35961. else {
  35962. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35963. }
  35964. // Instances
  35965. if (useInstances) {
  35966. defines.push("#define INSTANCES");
  35967. attribs.push("world0");
  35968. attribs.push("world1");
  35969. attribs.push("world2");
  35970. attribs.push("world3");
  35971. }
  35972. // Get correct effect
  35973. var join = defines.join("\n");
  35974. if (this._cachedDefines !== join) {
  35975. this._cachedDefines = join;
  35976. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  35977. }
  35978. return this._effect.isReady();
  35979. };
  35980. DepthRenderer.prototype.getDepthMap = function () {
  35981. return this._depthMap;
  35982. };
  35983. // Methods
  35984. DepthRenderer.prototype.dispose = function () {
  35985. this._depthMap.dispose();
  35986. };
  35987. return DepthRenderer;
  35988. })();
  35989. BABYLON.DepthRenderer = DepthRenderer;
  35990. })(BABYLON || (BABYLON = {}));
  35991. var BABYLON;
  35992. (function (BABYLON) {
  35993. var SSAORenderingPipeline = (function (_super) {
  35994. __extends(SSAORenderingPipeline, _super);
  35995. /**
  35996. * @constructor
  35997. * @param {string} name - The rendering pipeline name
  35998. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35999. * @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 }
  36000. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36001. */
  36002. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  36003. var _this = this;
  36004. _super.call(this, scene.getEngine(), name);
  36005. // Members
  36006. /**
  36007. * The PassPostProcess id in the pipeline that contains the original scene color
  36008. * @type {string}
  36009. */
  36010. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  36011. /**
  36012. * The SSAO PostProcess id in the pipeline
  36013. * @type {string}
  36014. */
  36015. this.SSAORenderEffect = "SSAORenderEffect";
  36016. /**
  36017. * The horizontal blur PostProcess id in the pipeline
  36018. * @type {string}
  36019. */
  36020. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  36021. /**
  36022. * The vertical blur PostProcess id in the pipeline
  36023. * @type {string}
  36024. */
  36025. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  36026. /**
  36027. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  36028. * @type {string}
  36029. */
  36030. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  36031. /**
  36032. * The output strength of the SSAO post-process. Default value is 1.0.
  36033. * @type {number}
  36034. */
  36035. this.totalStrength = 1.0;
  36036. /**
  36037. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  36038. * @type {number}
  36039. */
  36040. this.radius = 0.0001;
  36041. /**
  36042. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  36043. * Must not be equal to fallOff and superior to fallOff.
  36044. * Default value is 0.975
  36045. * @type {number}
  36046. */
  36047. this.area = 0.0075;
  36048. /**
  36049. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  36050. * Must not be equal to area and inferior to area.
  36051. * Default value is 0.0
  36052. * @type {number}
  36053. */
  36054. this.fallOff = 0.000001;
  36055. /**
  36056. * The base color of the SSAO post-process
  36057. * The final result is "base + ssao" between [0, 1]
  36058. * @type {number}
  36059. */
  36060. this.base = 0.5;
  36061. this._firstUpdate = true;
  36062. this._scene = scene;
  36063. // Set up assets
  36064. this._createRandomTexture();
  36065. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36066. var ssaoRatio = ratio.ssaoRatio || ratio;
  36067. var combineRatio = ratio.combineRatio || ratio;
  36068. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36069. this._createSSAOPostProcess(ssaoRatio);
  36070. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36071. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36072. this._createSSAOCombinePostProcess(combineRatio);
  36073. // Set up pipeline
  36074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  36075. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  36076. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  36077. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  36078. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  36079. // Finish
  36080. scene.postProcessRenderPipelineManager.addPipeline(this);
  36081. if (cameras)
  36082. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36083. }
  36084. // Public Methods
  36085. /**
  36086. * Returns the horizontal blur PostProcess
  36087. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  36088. */
  36089. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  36090. return this._blurHPostProcess;
  36091. };
  36092. /**
  36093. * Returns the vertical blur PostProcess
  36094. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  36095. */
  36096. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  36097. return this._blurVPostProcess;
  36098. };
  36099. /**
  36100. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  36101. */
  36102. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36103. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36104. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36105. this._originalColorPostProcess = undefined;
  36106. this._ssaoPostProcess = undefined;
  36107. this._blurHPostProcess = undefined;
  36108. this._blurVPostProcess = undefined;
  36109. this._ssaoCombinePostProcess = undefined;
  36110. this._randomTexture.dispose();
  36111. if (disableDepthRender)
  36112. this._scene.disableDepthRenderer();
  36113. };
  36114. // Private Methods
  36115. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  36116. var _this = this;
  36117. var numSamples = 16;
  36118. var sampleSphere = [
  36119. 0.5381, 0.1856, -0.4319,
  36120. 0.1379, 0.2486, 0.4430,
  36121. 0.3371, 0.5679, -0.0057,
  36122. -0.6999, -0.0451, -0.0019,
  36123. 0.0689, -0.1598, -0.8547,
  36124. 0.0560, 0.0069, -0.1843,
  36125. -0.0146, 0.1402, 0.0762,
  36126. 0.0100, -0.1924, -0.0344,
  36127. -0.3577, -0.5301, -0.4358,
  36128. -0.3169, 0.1063, 0.0158,
  36129. 0.0103, -0.5869, 0.0046,
  36130. -0.0897, -0.4940, 0.3287,
  36131. 0.7119, -0.0154, -0.0918,
  36132. -0.0533, 0.0596, -0.5411,
  36133. 0.0352, -0.0631, 0.5460,
  36134. -0.4776, 0.2847, -0.0271
  36135. ];
  36136. var samplesFactor = 1.0 / numSamples;
  36137. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  36138. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  36139. "area", "fallOff", "base"
  36140. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  36141. this._ssaoPostProcess.onApply = function (effect) {
  36142. if (_this._firstUpdate) {
  36143. effect.setArray3("sampleSphere", sampleSphere);
  36144. effect.setFloat("samplesFactor", samplesFactor);
  36145. effect.setFloat("randTextureTiles", 4.0);
  36146. _this._firstUpdate = false;
  36147. }
  36148. effect.setFloat("totalStrength", _this.totalStrength);
  36149. effect.setFloat("radius", _this.radius);
  36150. effect.setFloat("area", _this.area);
  36151. effect.setFloat("fallOff", _this.fallOff);
  36152. effect.setFloat("base", _this.base);
  36153. effect.setTexture("textureSampler", _this._depthTexture);
  36154. effect.setTexture("randomSampler", _this._randomTexture);
  36155. };
  36156. };
  36157. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  36158. var _this = this;
  36159. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36160. this._ssaoCombinePostProcess.onApply = function (effect) {
  36161. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  36162. };
  36163. };
  36164. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  36165. var size = 512;
  36166. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36167. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36168. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36169. var context = this._randomTexture.getContext();
  36170. var rand = function (min, max) {
  36171. return Math.random() * (max - min) + min;
  36172. };
  36173. var randVector = BABYLON.Vector3.Zero();
  36174. for (var x = 0; x < size; x++) {
  36175. for (var y = 0; y < size; y++) {
  36176. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  36177. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  36178. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  36179. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  36180. context.fillRect(x, y, 1, 1);
  36181. }
  36182. }
  36183. this._randomTexture.update(false);
  36184. };
  36185. return SSAORenderingPipeline;
  36186. })(BABYLON.PostProcessRenderPipeline);
  36187. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  36188. })(BABYLON || (BABYLON = {}));
  36189. var BABYLON;
  36190. (function (BABYLON) {
  36191. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  36192. var VolumetricLightScatteringPostProcess = (function (_super) {
  36193. __extends(VolumetricLightScatteringPostProcess, _super);
  36194. /**
  36195. * @constructor
  36196. * @param {string} name - The post-process name
  36197. * @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)
  36198. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  36199. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  36200. * @param {number} samples - The post-process quality, default 100
  36201. * @param {number} samplingMode - The post-process filtering mode
  36202. * @param {BABYLON.Engine} engine - The babylon engine
  36203. * @param {boolean} reusable - If the post-process is reusable
  36204. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  36205. */
  36206. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  36207. var _this = this;
  36208. if (samples === void 0) { samples = 100; }
  36209. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36210. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  36211. this._screenCoordinates = BABYLON.Vector2.Zero();
  36212. /**
  36213. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  36214. * @type {boolean}
  36215. */
  36216. this.useCustomMeshPosition = false;
  36217. /**
  36218. * If the post-process should inverse the light scattering direction
  36219. * @type {boolean}
  36220. */
  36221. this.invert = true;
  36222. /**
  36223. * Set to true to use the diffuseColor instead of the diffuseTexture
  36224. * @type {boolean}
  36225. */
  36226. this.useDiffuseColor = false;
  36227. /**
  36228. * Array containing the excluded meshes not rendered in the internal pass
  36229. */
  36230. this.excludedMeshes = new Array();
  36231. /**
  36232. * Controls the overall intensity of the post-process
  36233. * @type {number}
  36234. */
  36235. this.exposure = 0.3;
  36236. /**
  36237. * Dissipates each sample's contribution in range [0, 1]
  36238. * @type {number}
  36239. */
  36240. this.decay = 0.96815;
  36241. /**
  36242. * Controls the overall intensity of each sample
  36243. * @type {number}
  36244. */
  36245. this.weight = 0.58767;
  36246. /**
  36247. * Controls the density of each sample
  36248. * @type {number}
  36249. */
  36250. this.density = 0.926;
  36251. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  36252. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  36253. // Configure mesh
  36254. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  36255. // Configure
  36256. this._createPass(scene, ratio.passRatio || ratio);
  36257. this.onActivate = function (camera) {
  36258. if (!_this.isSupported) {
  36259. _this.dispose(camera);
  36260. }
  36261. _this.onActivate = null;
  36262. };
  36263. this.onApply = function (effect) {
  36264. _this._updateMeshScreenCoordinates(scene);
  36265. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  36266. effect.setFloat("exposure", _this.exposure);
  36267. effect.setFloat("decay", _this.decay);
  36268. effect.setFloat("weight", _this.weight);
  36269. effect.setFloat("density", _this.density);
  36270. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  36271. };
  36272. }
  36273. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  36274. var mesh = subMesh.getMesh();
  36275. var defines = [];
  36276. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36277. var material = subMesh.getMaterial();
  36278. var needUV = false;
  36279. // Render this.mesh as default
  36280. if (mesh === this.mesh) {
  36281. if (this.useDiffuseColor) {
  36282. defines.push("#define DIFFUSE_COLOR_RENDER");
  36283. }
  36284. else if (material) {
  36285. if (material.diffuseTexture !== undefined) {
  36286. defines.push("#define BASIC_RENDER");
  36287. }
  36288. else {
  36289. defines.push("#define DIFFUSE_COLOR_RENDER");
  36290. }
  36291. }
  36292. defines.push("#define NEED_UV");
  36293. needUV = true;
  36294. }
  36295. // Alpha test
  36296. if (material) {
  36297. if (material.needAlphaTesting()) {
  36298. defines.push("#define ALPHATEST");
  36299. }
  36300. if (material.opacityTexture !== undefined) {
  36301. defines.push("#define OPACITY");
  36302. if (material.opacityTexture.getAlphaFromRGB) {
  36303. defines.push("#define OPACITYRGB");
  36304. }
  36305. if (!needUV) {
  36306. defines.push("#define NEED_UV");
  36307. }
  36308. }
  36309. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36310. attribs.push(BABYLON.VertexBuffer.UVKind);
  36311. defines.push("#define UV1");
  36312. }
  36313. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36314. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36315. defines.push("#define UV2");
  36316. }
  36317. }
  36318. // Bones
  36319. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36320. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36321. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36322. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36323. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36324. }
  36325. else {
  36326. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36327. }
  36328. // Instances
  36329. if (useInstances) {
  36330. defines.push("#define INSTANCES");
  36331. attribs.push("world0");
  36332. attribs.push("world1");
  36333. attribs.push("world2");
  36334. attribs.push("world3");
  36335. }
  36336. // Get correct effect
  36337. var join = defines.join("\n");
  36338. if (this._cachedDefines !== join) {
  36339. this._cachedDefines = join;
  36340. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  36341. }
  36342. return this._volumetricLightScatteringPass.isReady();
  36343. };
  36344. /**
  36345. * Sets the new light position for light scattering effect
  36346. * @param {BABYLON.Vector3} The new custom light position
  36347. */
  36348. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  36349. this._customMeshPosition = position;
  36350. };
  36351. /**
  36352. * Returns the light position for light scattering effect
  36353. * @return {BABYLON.Vector3} The custom light position
  36354. */
  36355. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  36356. return this._customMeshPosition;
  36357. };
  36358. /**
  36359. * Disposes the internal assets and detaches the post-process from the camera
  36360. */
  36361. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  36362. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  36363. if (rttIndex !== -1) {
  36364. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  36365. }
  36366. this._volumetricLightScatteringRTT.dispose();
  36367. _super.prototype.dispose.call(this, camera);
  36368. };
  36369. /**
  36370. * Returns the render target texture used by the post-process
  36371. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  36372. */
  36373. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  36374. return this._volumetricLightScatteringRTT;
  36375. };
  36376. // Private methods
  36377. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  36378. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  36379. return true;
  36380. }
  36381. return false;
  36382. };
  36383. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  36384. var _this = this;
  36385. var engine = scene.getEngine();
  36386. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36387. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36388. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36389. this._volumetricLightScatteringRTT.renderList = null;
  36390. this._volumetricLightScatteringRTT.renderParticles = false;
  36391. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  36392. // Custom render function for submeshes
  36393. var renderSubMesh = function (subMesh) {
  36394. var mesh = subMesh.getRenderingMesh();
  36395. if (_this._meshExcluded(mesh)) {
  36396. return;
  36397. }
  36398. var scene = mesh.getScene();
  36399. var engine = scene.getEngine();
  36400. // Culling
  36401. engine.setState(subMesh.getMaterial().backFaceCulling);
  36402. // Managing instances
  36403. var batch = mesh._getInstancesRenderList(subMesh._id);
  36404. if (batch.mustReturn) {
  36405. return;
  36406. }
  36407. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36408. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36409. engine.enableEffect(_this._volumetricLightScatteringPass);
  36410. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  36411. var material = subMesh.getMaterial();
  36412. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  36413. // Alpha test
  36414. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  36415. var alphaTexture = material.getAlphaTestTexture();
  36416. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  36417. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  36418. }
  36419. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  36420. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  36421. if (alphaTexture) {
  36422. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36423. }
  36424. }
  36425. if (material.opacityTexture !== undefined) {
  36426. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  36427. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  36428. }
  36429. }
  36430. // Bones
  36431. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36432. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36433. }
  36434. // Draw
  36435. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  36436. }
  36437. };
  36438. // Render target texture callbacks
  36439. var savedSceneClearColor;
  36440. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  36441. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  36442. savedSceneClearColor = scene.clearColor;
  36443. scene.clearColor = sceneClearColor;
  36444. };
  36445. this._volumetricLightScatteringRTT.onAfterRender = function () {
  36446. scene.clearColor = savedSceneClearColor;
  36447. };
  36448. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  36449. var engine = scene.getEngine();
  36450. var index;
  36451. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36452. renderSubMesh(opaqueSubMeshes.data[index]);
  36453. }
  36454. engine.setAlphaTesting(true);
  36455. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36456. renderSubMesh(alphaTestSubMeshes.data[index]);
  36457. }
  36458. engine.setAlphaTesting(false);
  36459. if (transparentSubMeshes.length) {
  36460. // Sort sub meshes
  36461. for (index = 0; index < transparentSubMeshes.length; index++) {
  36462. var submesh = transparentSubMeshes.data[index];
  36463. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  36464. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  36465. }
  36466. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  36467. sortedArray.sort(function (a, b) {
  36468. // Alpha index first
  36469. if (a._alphaIndex > b._alphaIndex) {
  36470. return 1;
  36471. }
  36472. if (a._alphaIndex < b._alphaIndex) {
  36473. return -1;
  36474. }
  36475. // Then distance to camera
  36476. if (a._distanceToCamera < b._distanceToCamera) {
  36477. return 1;
  36478. }
  36479. if (a._distanceToCamera > b._distanceToCamera) {
  36480. return -1;
  36481. }
  36482. return 0;
  36483. });
  36484. // Render sub meshes
  36485. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36486. for (index = 0; index < sortedArray.length; index++) {
  36487. renderSubMesh(sortedArray[index]);
  36488. }
  36489. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36490. }
  36491. };
  36492. };
  36493. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  36494. var transform = scene.getTransformMatrix();
  36495. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  36496. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  36497. this._screenCoordinates.x = pos.x / this._viewPort.width;
  36498. this._screenCoordinates.y = pos.y / this._viewPort.height;
  36499. if (this.invert)
  36500. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  36501. };
  36502. // Static methods
  36503. /**
  36504. * Creates a default mesh for the Volumeric Light Scattering post-process
  36505. * @param {string} The mesh name
  36506. * @param {BABYLON.Scene} The scene where to create the mesh
  36507. * @return {BABYLON.Mesh} the default mesh
  36508. */
  36509. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  36510. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  36511. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  36512. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  36513. return mesh;
  36514. };
  36515. return VolumetricLightScatteringPostProcess;
  36516. })(BABYLON.PostProcess);
  36517. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  36518. })(BABYLON || (BABYLON = {}));
  36519. // BABYLON.JS Chromatic Aberration GLSL Shader
  36520. // Author: Olivier Guyot
  36521. // Separates very slightly R, G and B colors on the edges of the screen
  36522. // Inspired by Francois Tarlier & Martins Upitis
  36523. var BABYLON;
  36524. (function (BABYLON) {
  36525. var LensRenderingPipeline = (function (_super) {
  36526. __extends(LensRenderingPipeline, _super);
  36527. /**
  36528. * @constructor
  36529. *
  36530. * Effect parameters are as follow:
  36531. * {
  36532. * chromatic_aberration: number; // from 0 to x (1 for realism)
  36533. * edge_blur: number; // from 0 to x (1 for realism)
  36534. * distortion: number; // from 0 to x (1 for realism)
  36535. * grain_amount: number; // from 0 to 1
  36536. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  36537. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  36538. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  36539. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  36540. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  36541. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  36542. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  36543. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  36544. * }
  36545. * Note: if an effect parameter is unset, effect is disabled
  36546. *
  36547. * @param {string} name - The rendering pipeline name
  36548. * @param {object} parameters - An object containing all parameters (see above)
  36549. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36550. * @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)
  36551. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36552. */
  36553. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  36554. var _this = this;
  36555. if (ratio === void 0) { ratio = 1.0; }
  36556. _super.call(this, scene.getEngine(), name);
  36557. // Lens effects can be of the following:
  36558. // - chromatic aberration (slight shift of RGB colors)
  36559. // - blur on the edge of the lens
  36560. // - lens distortion
  36561. // - depth-of-field blur & highlights enhancing
  36562. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  36563. // - grain effect (noise or custom texture)
  36564. // Two additional texture samplers are needed:
  36565. // - depth map (for depth-of-field)
  36566. // - grain texture
  36567. /**
  36568. * The chromatic aberration PostProcess id in the pipeline
  36569. * @type {string}
  36570. */
  36571. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  36572. /**
  36573. * The highlights enhancing PostProcess id in the pipeline
  36574. * @type {string}
  36575. */
  36576. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  36577. /**
  36578. * The depth-of-field PostProcess id in the pipeline
  36579. * @type {string}
  36580. */
  36581. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  36582. this._scene = scene;
  36583. // Fetch texture samplers
  36584. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36585. if (parameters.grain_texture) {
  36586. this._grainTexture = parameters.grain_texture;
  36587. }
  36588. else {
  36589. this._createGrainTexture();
  36590. }
  36591. // save parameters
  36592. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  36593. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  36594. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  36595. this._distortion = parameters.distortion ? parameters.distortion : 0;
  36596. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  36597. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  36598. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  36599. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  36600. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  36601. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  36602. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  36603. // Create effects
  36604. this._createChromaticAberrationPostProcess(ratio);
  36605. this._createHighlightsPostProcess(ratio);
  36606. this._createDepthOfFieldPostProcess(ratio / 4);
  36607. // Set up pipeline
  36608. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  36609. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  36610. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  36611. if (this._highlightsGain === -1) {
  36612. this._disableEffect(this.HighlightsEnhancingEffect, null);
  36613. }
  36614. // Finish
  36615. scene.postProcessRenderPipelineManager.addPipeline(this);
  36616. if (cameras) {
  36617. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36618. }
  36619. }
  36620. // public methods (self explanatory)
  36621. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  36622. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  36623. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  36624. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  36625. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  36626. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  36627. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  36628. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  36629. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  36630. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  36631. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  36632. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  36633. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  36634. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  36635. };
  36636. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  36637. this._highlightsPostProcess.updateEffect();
  36638. };
  36639. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  36640. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  36641. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  36642. this._highlightsGain = amount;
  36643. };
  36644. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  36645. if (this._highlightsGain === -1) {
  36646. this._highlightsGain = 1.0;
  36647. }
  36648. this._highlightsThreshold = amount;
  36649. };
  36650. LensRenderingPipeline.prototype.disableHighlights = function () {
  36651. this._highlightsGain = -1;
  36652. };
  36653. /**
  36654. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  36655. */
  36656. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36657. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36658. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36659. this._chromaticAberrationPostProcess = undefined;
  36660. this._highlightsPostProcess = undefined;
  36661. this._depthOfFieldPostProcess = undefined;
  36662. this._grainTexture.dispose();
  36663. if (disableDepthRender)
  36664. this._scene.disableDepthRenderer();
  36665. };
  36666. // colors shifting and distortion
  36667. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  36668. var _this = this;
  36669. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  36670. [], // samplers
  36671. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36672. this._chromaticAberrationPostProcess.onApply = function (effect) {
  36673. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  36674. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36675. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36676. };
  36677. };
  36678. // highlights enhancing
  36679. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  36680. var _this = this;
  36681. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  36682. [], // samplers
  36683. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  36684. this._highlightsPostProcess.onApply = function (effect) {
  36685. effect.setFloat('gain', _this._highlightsGain);
  36686. effect.setFloat('threshold', _this._highlightsThreshold);
  36687. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  36688. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36689. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36690. };
  36691. };
  36692. // colors shifting and distortion
  36693. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  36694. var _this = this;
  36695. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  36696. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  36697. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  36698. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36699. this._depthOfFieldPostProcess.onApply = function (effect) {
  36700. effect.setTexture("depthSampler", _this._depthTexture);
  36701. effect.setTexture("grainSampler", _this._grainTexture);
  36702. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  36703. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  36704. effect.setFloat('grain_amount', _this._grainAmount);
  36705. effect.setBool('blur_noise', _this._blurNoise);
  36706. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36707. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36708. effect.setFloat('distortion', _this._distortion);
  36709. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  36710. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  36711. effect.setFloat('aperture', _this._dofAperture);
  36712. effect.setFloat('darken', _this._dofDarken);
  36713. effect.setFloat('edge_blur', _this._edgeBlur);
  36714. effect.setBool('highlights', (_this._highlightsGain !== -1));
  36715. effect.setFloat('near', _this._scene.activeCamera.minZ);
  36716. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  36717. };
  36718. };
  36719. // creates a black and white random noise texture, 512x512
  36720. LensRenderingPipeline.prototype._createGrainTexture = function () {
  36721. var size = 512;
  36722. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36723. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36724. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36725. var context = this._grainTexture.getContext();
  36726. var rand = function (min, max) {
  36727. return Math.random() * (max - min) + min;
  36728. };
  36729. var value;
  36730. for (var x = 0; x < size; x++) {
  36731. for (var y = 0; y < size; y++) {
  36732. value = Math.floor(rand(0.42, 0.58) * 255);
  36733. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  36734. context.fillRect(x, y, 1, 1);
  36735. }
  36736. }
  36737. this._grainTexture.update(false);
  36738. };
  36739. return LensRenderingPipeline;
  36740. })(BABYLON.PostProcessRenderPipeline);
  36741. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  36742. })(BABYLON || (BABYLON = {}));
  36743. //
  36744. // This post-process allows the modification of rendered colors by using
  36745. // a 'look-up table' (LUT). This effect is also called Color Grading.
  36746. //
  36747. // The object needs to be provided an url to a texture containing the color
  36748. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  36749. // Use an image editing software to tweak the LUT to match your needs.
  36750. //
  36751. // For an example of a color LUT, see here:
  36752. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  36753. // For explanations on color grading, see here:
  36754. // http://udn.epicgames.com/Three/ColorGrading.html
  36755. //
  36756. var BABYLON;
  36757. (function (BABYLON) {
  36758. var ColorCorrectionPostProcess = (function (_super) {
  36759. __extends(ColorCorrectionPostProcess, _super);
  36760. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  36761. var _this = this;
  36762. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  36763. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36764. this._colorTableTexture.anisotropicFilteringLevel = 1;
  36765. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36766. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36767. this.onApply = function (effect) {
  36768. effect.setTexture("colorTable", _this._colorTableTexture);
  36769. };
  36770. }
  36771. return ColorCorrectionPostProcess;
  36772. })(BABYLON.PostProcess);
  36773. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  36774. })(BABYLON || (BABYLON = {}));
  36775. var BABYLON;
  36776. (function (BABYLON) {
  36777. var HDRRenderingPipeline = (function (_super) {
  36778. __extends(HDRRenderingPipeline, _super);
  36779. /**
  36780. * @constructor
  36781. * @param {string} name - The rendering pipeline name
  36782. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36783. * @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)
  36784. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  36785. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36786. */
  36787. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  36788. var _this = this;
  36789. if (originalPostProcess === void 0) { originalPostProcess = null; }
  36790. _super.call(this, scene.getEngine(), name);
  36791. /**
  36792. * Public members
  36793. */
  36794. // Gaussian Blur
  36795. /**
  36796. * Gaussian blur coefficient
  36797. * @type {number}
  36798. */
  36799. this.gaussCoeff = 0.3;
  36800. /**
  36801. * Gaussian blur mean
  36802. * @type {number}
  36803. */
  36804. this.gaussMean = 1.0;
  36805. /**
  36806. * Gaussian blur standard deviation
  36807. * @type {number}
  36808. */
  36809. this.gaussStandDev = 0.8;
  36810. /**
  36811. * Gaussian blur multiplier. Multiplies the blur effect
  36812. * @type {number}
  36813. */
  36814. this.gaussMultiplier = 4.0;
  36815. // HDR
  36816. /**
  36817. * Exposure, controls the overall intensity of the pipeline
  36818. * @type {number}
  36819. */
  36820. this.exposure = 1.0;
  36821. /**
  36822. * Minimum luminance that the post-process can output. Luminance is >= 0
  36823. * @type {number}
  36824. */
  36825. this.minimumLuminance = 1.0;
  36826. /**
  36827. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  36828. * @type {number}
  36829. */
  36830. this.maximumLuminance = 1e20;
  36831. /**
  36832. * Increase rate for luminance: eye adaptation speed to dark
  36833. * @type {number}
  36834. */
  36835. this.luminanceIncreaserate = 0.5;
  36836. /**
  36837. * Decrease rate for luminance: eye adaptation speed to bright
  36838. * @type {number}
  36839. */
  36840. this.luminanceDecreaseRate = 0.5;
  36841. // Bright pass
  36842. /**
  36843. * Minimum luminance needed to compute HDR
  36844. * @type {number}
  36845. */
  36846. this.brightThreshold = 0.8;
  36847. this._needUpdate = true;
  36848. this._scene = scene;
  36849. // Bright pass
  36850. this._createBrightPassPostProcess(scene, ratio);
  36851. // Down sample X4
  36852. this._createDownSampleX4PostProcess(scene, ratio);
  36853. // Create gaussian blur post-processes
  36854. this._createGaussianBlurPostProcess(scene, ratio);
  36855. // Texture adder
  36856. this._createTextureAdderPostProcess(scene, ratio);
  36857. // Luminance generator
  36858. this._createLuminanceGeneratorPostProcess(scene);
  36859. // HDR
  36860. this._createHDRPostProcess(scene, ratio);
  36861. // Pass postprocess
  36862. if (originalPostProcess === null) {
  36863. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36864. }
  36865. else {
  36866. this._originalPostProcess = originalPostProcess;
  36867. }
  36868. // Configure pipeline
  36869. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  36870. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  36871. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  36872. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  36873. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  36874. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  36875. var addDownSamplerPostProcess = function (id) {
  36876. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  36877. };
  36878. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36879. addDownSamplerPostProcess(i);
  36880. }
  36881. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  36882. // Finish
  36883. scene.postProcessRenderPipelineManager.addPipeline(this);
  36884. if (cameras !== null) {
  36885. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36886. }
  36887. this.update();
  36888. }
  36889. /**
  36890. * Tells the pipeline to update its post-processes
  36891. */
  36892. HDRRenderingPipeline.prototype.update = function () {
  36893. this._needUpdate = true;
  36894. };
  36895. /**
  36896. * Returns the current calculated luminance
  36897. */
  36898. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36899. return this._hdrCurrentLuminance;
  36900. };
  36901. /**
  36902. * Returns the currently drawn luminance
  36903. */
  36904. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36905. return this._hdrOutputLuminance;
  36906. };
  36907. /**
  36908. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36909. */
  36910. HDRRenderingPipeline.prototype.dispose = function () {
  36911. this._originalPostProcess = undefined;
  36912. this._brightPassPostProcess = undefined;
  36913. this._downSampleX4PostProcess = undefined;
  36914. this._guassianBlurHPostProcess = undefined;
  36915. this._guassianBlurVPostProcess = undefined;
  36916. this._textureAdderPostProcess = undefined;
  36917. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36918. this._downSamplePostProcesses[i] = undefined;
  36919. }
  36920. this._hdrPostProcess = undefined;
  36921. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36922. };
  36923. /**
  36924. * Creates the HDR post-process and computes the luminance adaptation
  36925. */
  36926. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36927. var _this = this;
  36928. var hdrLastLuminance = 0.0;
  36929. this._hdrOutputLuminance = -1.0;
  36930. this._hdrCurrentLuminance = 1.0;
  36931. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36932. this._hdrPostProcess.onApply = function (effect) {
  36933. if (_this._hdrOutputLuminance < 0.0) {
  36934. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36935. }
  36936. else {
  36937. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36938. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36939. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36940. }
  36941. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36942. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36943. }
  36944. else {
  36945. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36946. }
  36947. }
  36948. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36949. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36950. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36951. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36952. effect.setFloat("exposure", _this.exposure);
  36953. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36954. _this._needUpdate = false;
  36955. };
  36956. };
  36957. /**
  36958. * Texture Adder post-process
  36959. */
  36960. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36961. var _this = this;
  36962. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36963. this._textureAdderPostProcess.onApply = function (effect) {
  36964. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36965. };
  36966. };
  36967. /**
  36968. * Down sample X4 post-process
  36969. */
  36970. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36971. var _this = this;
  36972. var downSampleX4Offsets = new Array(32);
  36973. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36974. this._downSampleX4PostProcess.onApply = function (effect) {
  36975. if (_this._needUpdate) {
  36976. var id = 0;
  36977. for (var i = -2; i < 2; i++) {
  36978. for (var j = -2; j < 2; j++) {
  36979. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36980. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36981. id += 2;
  36982. }
  36983. }
  36984. }
  36985. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36986. };
  36987. };
  36988. /**
  36989. * Bright pass post-process
  36990. */
  36991. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36992. var _this = this;
  36993. var brightOffsets = new Array(8);
  36994. var brightPassCallback = function (effect) {
  36995. if (_this._needUpdate) {
  36996. var sU = (1.0 / _this._brightPassPostProcess.width);
  36997. var sV = (1.0 / _this._brightPassPostProcess.height);
  36998. brightOffsets[0] = -0.5 * sU;
  36999. brightOffsets[1] = 0.5 * sV;
  37000. brightOffsets[2] = 0.5 * sU;
  37001. brightOffsets[3] = 0.5 * sV;
  37002. brightOffsets[4] = -0.5 * sU;
  37003. brightOffsets[5] = -0.5 * sV;
  37004. brightOffsets[6] = 0.5 * sU;
  37005. brightOffsets[7] = -0.5 * sV;
  37006. }
  37007. effect.setArray2("dsOffsets", brightOffsets);
  37008. effect.setFloat("brightThreshold", _this.brightThreshold);
  37009. };
  37010. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  37011. this._brightPassPostProcess.onApply = brightPassCallback;
  37012. };
  37013. /**
  37014. * Luminance generator. Creates the luminance post-process and down sample post-processes
  37015. */
  37016. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  37017. var _this = this;
  37018. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  37019. var luminanceOffsets = new Array(8);
  37020. var downSampleOffsets = new Array(18);
  37021. var halfDestPixelSize;
  37022. this._downSamplePostProcesses = new Array(lumSteps);
  37023. // Utils for luminance
  37024. var luminanceUpdateSourceOffsets = function (width, height) {
  37025. var sU = (1.0 / width);
  37026. var sV = (1.0 / height);
  37027. luminanceOffsets[0] = -0.5 * sU;
  37028. luminanceOffsets[1] = 0.5 * sV;
  37029. luminanceOffsets[2] = 0.5 * sU;
  37030. luminanceOffsets[3] = 0.5 * sV;
  37031. luminanceOffsets[4] = -0.5 * sU;
  37032. luminanceOffsets[5] = -0.5 * sV;
  37033. luminanceOffsets[6] = 0.5 * sU;
  37034. luminanceOffsets[7] = -0.5 * sV;
  37035. };
  37036. var luminanceUpdateDestOffsets = function (width, height) {
  37037. var id = 0;
  37038. for (var x = -1; x < 2; x++) {
  37039. for (var y = -1; y < 2; y++) {
  37040. downSampleOffsets[id] = (x) / width;
  37041. downSampleOffsets[id + 1] = (y) / height;
  37042. id += 2;
  37043. }
  37044. }
  37045. };
  37046. // Luminance callback
  37047. var luminanceCallback = function (effect) {
  37048. if (_this._needUpdate) {
  37049. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  37050. }
  37051. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37052. effect.setArray2("lumOffsets", luminanceOffsets);
  37053. };
  37054. // Down sample callbacks
  37055. var downSampleCallback = function (indice) {
  37056. var i = indice;
  37057. return function (effect) {
  37058. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37059. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37060. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  37061. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  37062. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  37063. effect.setArray2("dsOffsets", downSampleOffsets);
  37064. };
  37065. };
  37066. var downSampleAfterRenderCallback = function (effect) {
  37067. // Unpack result
  37068. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  37069. 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);
  37070. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  37071. };
  37072. // Create luminance post-process
  37073. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  37074. 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);
  37075. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  37076. // Create down sample post-processes
  37077. for (var i = lumSteps - 2; i >= 0; i--) {
  37078. var length = Math.pow(3, i);
  37079. ratio = { width: length, height: length };
  37080. var defines = "#define DOWN_SAMPLE\n";
  37081. if (i === 0) {
  37082. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  37083. }
  37084. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  37085. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  37086. if (i === 0) {
  37087. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  37088. }
  37089. }
  37090. };
  37091. /**
  37092. * Gaussian blur post-processes. Horizontal and Vertical
  37093. */
  37094. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  37095. var _this = this;
  37096. var blurOffsetsW = new Array(9);
  37097. var blurOffsetsH = new Array(9);
  37098. var blurWeights = new Array(9);
  37099. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  37100. // Utils for gaussian blur
  37101. var calculateBlurOffsets = function (height) {
  37102. var lastOutputDimensions = {
  37103. width: scene.getEngine().getRenderWidth(),
  37104. height: scene.getEngine().getRenderHeight()
  37105. };
  37106. for (var i = 0; i < 9; i++) {
  37107. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  37108. if (height) {
  37109. blurOffsetsH[i] = value;
  37110. }
  37111. else {
  37112. blurOffsetsW[i] = value;
  37113. }
  37114. }
  37115. };
  37116. var calculateWeights = function () {
  37117. var x = 0.0;
  37118. for (var i = 0; i < 9; i++) {
  37119. x = (i - 4.0) / 4.0;
  37120. 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));
  37121. }
  37122. };
  37123. // Callback
  37124. var gaussianBlurCallback = function (height) {
  37125. return function (effect) {
  37126. if (_this._needUpdate) {
  37127. calculateWeights();
  37128. calculateBlurOffsets(height);
  37129. }
  37130. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  37131. effect.setArray("blurWeights", blurWeights);
  37132. effect.setFloat("multiplier", _this.gaussMultiplier);
  37133. };
  37134. };
  37135. // Create horizontal gaussian blur post-processes
  37136. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  37137. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  37138. // Create vertical gaussian blur post-process
  37139. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  37140. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  37141. };
  37142. // Luminance generator
  37143. HDRRenderingPipeline.LUM_STEPS = 6;
  37144. return HDRRenderingPipeline;
  37145. })(BABYLON.PostProcessRenderPipeline);
  37146. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  37147. })(BABYLON || (BABYLON = {}));
  37148. var BABYLON;
  37149. (function (BABYLON) {
  37150. var FaceAdjacencies = (function () {
  37151. function FaceAdjacencies() {
  37152. this.edges = new Array();
  37153. this.edgesConnectedCount = 0;
  37154. }
  37155. return FaceAdjacencies;
  37156. })();
  37157. var EdgesRenderer = (function () {
  37158. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  37159. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  37160. if (epsilon === void 0) { epsilon = 0.95; }
  37161. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  37162. this.edgesWidthScalerForOrthographic = 1000.0;
  37163. this.edgesWidthScalerForPerspective = 50.0;
  37164. this._linesPositions = new Array();
  37165. this._linesNormals = new Array();
  37166. this._linesIndices = new Array();
  37167. this._buffers = new Array();
  37168. this._checkVerticesInsteadOfIndices = false;
  37169. this._source = source;
  37170. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  37171. this._epsilon = epsilon;
  37172. this._prepareRessources();
  37173. this._generateEdgesLines();
  37174. }
  37175. EdgesRenderer.prototype._prepareRessources = function () {
  37176. if (this._lineShader) {
  37177. return;
  37178. }
  37179. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  37180. attributes: ["position", "normal"],
  37181. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  37182. });
  37183. this._lineShader.disableDepthWrite = true;
  37184. this._lineShader.backFaceCulling = false;
  37185. };
  37186. EdgesRenderer.prototype.dispose = function () {
  37187. this._vb0.dispose();
  37188. this._vb1.dispose();
  37189. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  37190. this._lineShader.dispose();
  37191. };
  37192. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  37193. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  37194. return 0;
  37195. }
  37196. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  37197. return 1;
  37198. }
  37199. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  37200. return 2;
  37201. }
  37202. return -1;
  37203. };
  37204. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  37205. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  37206. return 0;
  37207. }
  37208. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  37209. return 1;
  37210. }
  37211. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  37212. return 2;
  37213. }
  37214. return -1;
  37215. };
  37216. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  37217. var needToCreateLine;
  37218. if (edge === undefined) {
  37219. needToCreateLine = true;
  37220. }
  37221. else {
  37222. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  37223. needToCreateLine = dotProduct < this._epsilon;
  37224. }
  37225. if (needToCreateLine) {
  37226. var offset = this._linesPositions.length / 3;
  37227. var normal = p0.subtract(p1);
  37228. normal.normalize();
  37229. // Positions
  37230. this._linesPositions.push(p0.x);
  37231. this._linesPositions.push(p0.y);
  37232. this._linesPositions.push(p0.z);
  37233. this._linesPositions.push(p0.x);
  37234. this._linesPositions.push(p0.y);
  37235. this._linesPositions.push(p0.z);
  37236. this._linesPositions.push(p1.x);
  37237. this._linesPositions.push(p1.y);
  37238. this._linesPositions.push(p1.z);
  37239. this._linesPositions.push(p1.x);
  37240. this._linesPositions.push(p1.y);
  37241. this._linesPositions.push(p1.z);
  37242. // Normals
  37243. this._linesNormals.push(p1.x);
  37244. this._linesNormals.push(p1.y);
  37245. this._linesNormals.push(p1.z);
  37246. this._linesNormals.push(-1);
  37247. this._linesNormals.push(p1.x);
  37248. this._linesNormals.push(p1.y);
  37249. this._linesNormals.push(p1.z);
  37250. this._linesNormals.push(1);
  37251. this._linesNormals.push(p0.x);
  37252. this._linesNormals.push(p0.y);
  37253. this._linesNormals.push(p0.z);
  37254. this._linesNormals.push(-1);
  37255. this._linesNormals.push(p0.x);
  37256. this._linesNormals.push(p0.y);
  37257. this._linesNormals.push(p0.z);
  37258. this._linesNormals.push(1);
  37259. // Indices
  37260. this._linesIndices.push(offset);
  37261. this._linesIndices.push(offset + 1);
  37262. this._linesIndices.push(offset + 2);
  37263. this._linesIndices.push(offset);
  37264. this._linesIndices.push(offset + 2);
  37265. this._linesIndices.push(offset + 3);
  37266. }
  37267. };
  37268. EdgesRenderer.prototype._generateEdgesLines = function () {
  37269. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37270. var indices = this._source.getIndices();
  37271. // First let's find adjacencies
  37272. var adjacencies = new Array();
  37273. var faceNormals = new Array();
  37274. var index;
  37275. var faceAdjacencies;
  37276. // Prepare faces
  37277. for (index = 0; index < indices.length; index += 3) {
  37278. faceAdjacencies = new FaceAdjacencies();
  37279. var p0Index = indices[index];
  37280. var p1Index = indices[index + 1];
  37281. var p2Index = indices[index + 2];
  37282. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  37283. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  37284. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  37285. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  37286. faceNormal.normalize();
  37287. faceNormals.push(faceNormal);
  37288. adjacencies.push(faceAdjacencies);
  37289. }
  37290. // Scan
  37291. for (index = 0; index < adjacencies.length; index++) {
  37292. faceAdjacencies = adjacencies[index];
  37293. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  37294. var otherFaceAdjacencies = adjacencies[otherIndex];
  37295. if (faceAdjacencies.edgesConnectedCount === 3) {
  37296. break;
  37297. }
  37298. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  37299. continue;
  37300. }
  37301. var otherP0 = indices[otherIndex * 3];
  37302. var otherP1 = indices[otherIndex * 3 + 1];
  37303. var otherP2 = indices[otherIndex * 3 + 2];
  37304. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  37305. var otherEdgeIndex;
  37306. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  37307. continue;
  37308. }
  37309. switch (edgeIndex) {
  37310. case 0:
  37311. if (this._checkVerticesInsteadOfIndices) {
  37312. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37313. }
  37314. else {
  37315. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  37316. }
  37317. break;
  37318. case 1:
  37319. if (this._checkVerticesInsteadOfIndices) {
  37320. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37321. }
  37322. else {
  37323. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  37324. }
  37325. break;
  37326. case 2:
  37327. if (this._checkVerticesInsteadOfIndices) {
  37328. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37329. }
  37330. else {
  37331. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  37332. }
  37333. break;
  37334. }
  37335. if (otherEdgeIndex === -1) {
  37336. continue;
  37337. }
  37338. faceAdjacencies.edges[edgeIndex] = otherIndex;
  37339. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  37340. faceAdjacencies.edgesConnectedCount++;
  37341. otherFaceAdjacencies.edgesConnectedCount++;
  37342. if (faceAdjacencies.edgesConnectedCount === 3) {
  37343. break;
  37344. }
  37345. }
  37346. }
  37347. }
  37348. // Create lines
  37349. for (index = 0; index < adjacencies.length; index++) {
  37350. // 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
  37351. var current = adjacencies[index];
  37352. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  37353. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  37354. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  37355. }
  37356. // Merge into a single mesh
  37357. var engine = this._source.getScene().getEngine();
  37358. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  37359. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  37360. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  37361. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  37362. this._ib = engine.createIndexBuffer(this._linesIndices);
  37363. this._indicesCount = this._linesIndices.length;
  37364. };
  37365. EdgesRenderer.prototype.render = function () {
  37366. if (!this._lineShader.isReady()) {
  37367. return;
  37368. }
  37369. var scene = this._source.getScene();
  37370. var engine = scene.getEngine();
  37371. this._lineShader._preBind();
  37372. // VBOs
  37373. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  37374. scene.resetCachedMaterial();
  37375. this._lineShader.setColor4("color", this._source.edgesColor);
  37376. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  37377. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  37378. }
  37379. else {
  37380. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  37381. }
  37382. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  37383. this._lineShader.bind(this._source.getWorldMatrix());
  37384. // Draw order
  37385. engine.draw(true, 0, this._indicesCount);
  37386. this._lineShader.unbind();
  37387. engine.setDepthWrite(true);
  37388. };
  37389. return EdgesRenderer;
  37390. })();
  37391. BABYLON.EdgesRenderer = EdgesRenderer;
  37392. })(BABYLON || (BABYLON = {}));
  37393. var BABYLON;
  37394. (function (BABYLON) {
  37395. (function (TonemappingOperator) {
  37396. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  37397. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  37398. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  37399. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  37400. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  37401. var TonemappingOperator = BABYLON.TonemappingOperator;
  37402. ;
  37403. var TonemapPostProcess = (function (_super) {
  37404. __extends(TonemapPostProcess, _super);
  37405. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  37406. var _this = this;
  37407. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37408. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37409. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  37410. this._operator = _operator;
  37411. this.exposureAdjustment = exposureAdjustment;
  37412. var defines = "#define ";
  37413. if (this._operator === TonemappingOperator.Hable)
  37414. defines += "HABLE_TONEMAPPING";
  37415. else if (this._operator === TonemappingOperator.Reinhard)
  37416. defines += "REINHARD_TONEMAPPING";
  37417. else if (this._operator === TonemappingOperator.HejiDawson)
  37418. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  37419. else if (this._operator === TonemappingOperator.Photographic)
  37420. defines += "PHOTOGRAPHIC_TONEMAPPING";
  37421. //sadly a second call to create the effect.
  37422. this.updateEffect(defines);
  37423. this.onApply = function (effect) {
  37424. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  37425. };
  37426. }
  37427. return TonemapPostProcess;
  37428. })(BABYLON.PostProcess);
  37429. BABYLON.TonemapPostProcess = TonemapPostProcess;
  37430. })(BABYLON || (BABYLON = {}));
  37431. var BABYLON;
  37432. (function (BABYLON) {
  37433. var ReflectionProbe = (function () {
  37434. function ReflectionProbe(name, size, scene, generateMipMaps) {
  37435. var _this = this;
  37436. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37437. this.name = name;
  37438. this._viewMatrix = BABYLON.Matrix.Identity();
  37439. this._target = BABYLON.Vector3.Zero();
  37440. this._add = BABYLON.Vector3.Zero();
  37441. this.position = BABYLON.Vector3.Zero();
  37442. this._scene = scene;
  37443. this._scene.reflectionProbes.push(this);
  37444. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  37445. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  37446. switch (faceIndex) {
  37447. case 0:
  37448. _this._add.copyFromFloats(1, 0, 0);
  37449. break;
  37450. case 1:
  37451. _this._add.copyFromFloats(-1, 0, 0);
  37452. break;
  37453. case 2:
  37454. _this._add.copyFromFloats(0, -1, 0);
  37455. break;
  37456. case 3:
  37457. _this._add.copyFromFloats(0, 1, 0);
  37458. break;
  37459. case 4:
  37460. _this._add.copyFromFloats(0, 0, 1);
  37461. break;
  37462. case 5:
  37463. _this._add.copyFromFloats(0, 0, -1);
  37464. break;
  37465. }
  37466. if (_this._attachedMesh) {
  37467. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  37468. }
  37469. _this.position.addToRef(_this._add, _this._target);
  37470. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  37471. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  37472. };
  37473. this._renderTargetTexture.onAfterUnbind = function () {
  37474. scene.updateTransformMatrix(true);
  37475. };
  37476. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  37477. }
  37478. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  37479. get: function () {
  37480. return this._renderTargetTexture.refreshRate;
  37481. },
  37482. set: function (value) {
  37483. this._renderTargetTexture.refreshRate = value;
  37484. },
  37485. enumerable: true,
  37486. configurable: true
  37487. });
  37488. ReflectionProbe.prototype.getScene = function () {
  37489. return this._scene;
  37490. };
  37491. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  37492. get: function () {
  37493. return this._renderTargetTexture;
  37494. },
  37495. enumerable: true,
  37496. configurable: true
  37497. });
  37498. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  37499. get: function () {
  37500. return this._renderTargetTexture.renderList;
  37501. },
  37502. enumerable: true,
  37503. configurable: true
  37504. });
  37505. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  37506. this._attachedMesh = mesh;
  37507. };
  37508. ReflectionProbe.prototype.dispose = function () {
  37509. var index = this._scene.reflectionProbes.indexOf(this);
  37510. if (index !== -1) {
  37511. // Remove from the scene if found
  37512. this._scene.reflectionProbes.splice(index, 1);
  37513. }
  37514. if (this._renderTargetTexture) {
  37515. this._renderTargetTexture.dispose();
  37516. this._renderTargetTexture = null;
  37517. }
  37518. };
  37519. return ReflectionProbe;
  37520. })();
  37521. BABYLON.ReflectionProbe = ReflectionProbe;
  37522. })(BABYLON || (BABYLON = {}));
  37523. var BABYLON;
  37524. (function (BABYLON) {
  37525. var SolidParticle = (function () {
  37526. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  37527. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  37528. this.position = BABYLON.Vector3.Zero(); // position
  37529. this.rotation = BABYLON.Vector3.Zero(); // rotation
  37530. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  37531. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  37532. this.velocity = BABYLON.Vector3.Zero(); // velocity
  37533. this.alive = true; // alive
  37534. this.idx = particleIndex;
  37535. this._pos = positionIndex;
  37536. this._model = model;
  37537. this.shapeId = shapeId;
  37538. this.idxInShape = idxInShape;
  37539. }
  37540. return SolidParticle;
  37541. })();
  37542. BABYLON.SolidParticle = SolidParticle;
  37543. var ModelShape = (function () {
  37544. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  37545. this.shapeID = id;
  37546. this._shape = shape;
  37547. this._shapeUV = shapeUV;
  37548. this._positionFunction = posFunction;
  37549. this._vertexFunction = vtxFunction;
  37550. }
  37551. return ModelShape;
  37552. })();
  37553. BABYLON.ModelShape = ModelShape;
  37554. })(BABYLON || (BABYLON = {}));
  37555. var BABYLON;
  37556. (function (BABYLON) {
  37557. /**
  37558. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  37559. */
  37560. var SolidParticleSystem = (function () {
  37561. /**
  37562. * Creates a SPS (Solid Particle System) object.
  37563. * @param name the SPS name, this will be the underlying mesh name
  37564. * @param scene the scene in which the SPS is added
  37565. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  37566. */
  37567. function SolidParticleSystem(name, scene, options) {
  37568. // public members
  37569. /**
  37570. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  37571. * Example : var p = SPS.particles[i];
  37572. */
  37573. this.particles = new Array();
  37574. /**
  37575. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  37576. */
  37577. this.nbParticles = 0;
  37578. /**
  37579. * If the particles must ever face the camera (default false). Useful for planar particles.
  37580. */
  37581. this.billboard = false;
  37582. /**
  37583. * This a counter ofr your own usage. It's not set by any SPS functions.
  37584. */
  37585. this.counter = 0;
  37586. /**
  37587. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  37588. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  37589. */
  37590. this.vars = {};
  37591. this._positions = new Array();
  37592. this._indices = new Array();
  37593. this._normals = new Array();
  37594. this._colors = new Array();
  37595. this._uvs = new Array();
  37596. this._index = 0; // indices index
  37597. this._updatable = true;
  37598. this._pickable = false;
  37599. this._isVisibilityBoxLocked = false;
  37600. this._alwaysVisible = false;
  37601. this._shapeCounter = 0;
  37602. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  37603. this._color = new BABYLON.Color4(0, 0, 0, 0);
  37604. this._computeParticleColor = true;
  37605. this._computeParticleTexture = true;
  37606. this._computeParticleRotation = true;
  37607. this._computeParticleVertex = false;
  37608. this._computeBoundingBox = false;
  37609. this._cam_axisZ = BABYLON.Vector3.Zero();
  37610. this._cam_axisY = BABYLON.Vector3.Zero();
  37611. this._cam_axisX = BABYLON.Vector3.Zero();
  37612. this._axisX = BABYLON.Axis.X;
  37613. this._axisY = BABYLON.Axis.Y;
  37614. this._axisZ = BABYLON.Axis.Z;
  37615. this._fakeCamPos = BABYLON.Vector3.Zero();
  37616. this._rotMatrix = new BABYLON.Matrix();
  37617. this._invertMatrix = new BABYLON.Matrix();
  37618. this._rotated = BABYLON.Vector3.Zero();
  37619. this._quaternion = new BABYLON.Quaternion();
  37620. this._vertex = BABYLON.Vector3.Zero();
  37621. this._normal = BABYLON.Vector3.Zero();
  37622. this._yaw = 0.0;
  37623. this._pitch = 0.0;
  37624. this._roll = 0.0;
  37625. this._halfroll = 0.0;
  37626. this._halfpitch = 0.0;
  37627. this._halfyaw = 0.0;
  37628. this._sinRoll = 0.0;
  37629. this._cosRoll = 0.0;
  37630. this._sinPitch = 0.0;
  37631. this._cosPitch = 0.0;
  37632. this._sinYaw = 0.0;
  37633. this._cosYaw = 0.0;
  37634. this._w = 0.0;
  37635. this._minimum = BABYLON.Tmp.Vector3[0];
  37636. this._maximum = BABYLON.Tmp.Vector3[1];
  37637. this.name = name;
  37638. this._scene = scene;
  37639. this._camera = scene.activeCamera;
  37640. this._pickable = options ? options.isPickable : false;
  37641. if (options && options.updatable) {
  37642. this._updatable = options.updatable;
  37643. }
  37644. else {
  37645. this._updatable = true;
  37646. }
  37647. if (this._pickable) {
  37648. this.pickedParticles = [];
  37649. }
  37650. }
  37651. /**
  37652. * Builds the SPS underlying mesh. Returns a standard Mesh.
  37653. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  37654. */
  37655. SolidParticleSystem.prototype.buildMesh = function () {
  37656. if (this.nbParticles === 0) {
  37657. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  37658. this.addShape(triangle, 1);
  37659. triangle.dispose();
  37660. }
  37661. this._positions32 = new Float32Array(this._positions);
  37662. this._uvs32 = new Float32Array(this._uvs);
  37663. this._colors32 = new Float32Array(this._colors);
  37664. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  37665. this._normals32 = new Float32Array(this._normals);
  37666. this._fixedNormal32 = new Float32Array(this._normals);
  37667. var vertexData = new BABYLON.VertexData();
  37668. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  37669. vertexData.indices = this._indices;
  37670. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  37671. if (this._uvs32) {
  37672. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  37673. ;
  37674. }
  37675. if (this._colors32) {
  37676. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  37677. }
  37678. var mesh = new BABYLON.Mesh(this.name, this._scene);
  37679. vertexData.applyToMesh(mesh, this._updatable);
  37680. this.mesh = mesh;
  37681. this.mesh.isPickable = this._pickable;
  37682. // free memory
  37683. this._positions = null;
  37684. this._normals = null;
  37685. this._uvs = null;
  37686. this._colors = null;
  37687. if (!this._updatable) {
  37688. this.particles.length = 0;
  37689. }
  37690. return mesh;
  37691. };
  37692. /**
  37693. * Digests the mesh and generates as many solid particles in the system as wanted.
  37694. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  37695. * Thus the particles generated from digest() have their property "positiion" yet set.
  37696. * @param mesh the mesh to be digested
  37697. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  37698. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  37699. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  37700. */
  37701. SolidParticleSystem.prototype.digest = function (mesh, options) {
  37702. var size = (options && options.facetNb) || 1;
  37703. var number = (options && options.number);
  37704. var delta = (options && options.delta) || 0;
  37705. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37706. var meshInd = mesh.getIndices();
  37707. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37708. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37709. var f = 0; // facet counter
  37710. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  37711. // compute size from number
  37712. if (number) {
  37713. number = (number > totalFacets) ? totalFacets : number;
  37714. size = Math.round(totalFacets / number);
  37715. delta = 0;
  37716. }
  37717. else {
  37718. size = (size > totalFacets) ? totalFacets : size;
  37719. }
  37720. var facetPos = []; // submesh positions
  37721. var facetInd = []; // submesh indices
  37722. var facetUV = []; // submesh UV
  37723. var facetCol = []; // submesh colors
  37724. var barycenter = BABYLON.Tmp.Vector3[0];
  37725. var rand;
  37726. var sizeO = size;
  37727. while (f < totalFacets) {
  37728. size = sizeO + Math.floor((1 + delta) * Math.random());
  37729. if (f > totalFacets - size) {
  37730. size = totalFacets - f;
  37731. }
  37732. // reset temp arrays
  37733. facetPos.length = 0;
  37734. facetInd.length = 0;
  37735. facetUV.length = 0;
  37736. facetCol.length = 0;
  37737. // iterate over "size" facets
  37738. var fi = 0;
  37739. for (var j = f * 3; j < (f + size) * 3; j++) {
  37740. facetInd.push(fi);
  37741. var i = meshInd[j];
  37742. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  37743. if (meshUV) {
  37744. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  37745. }
  37746. if (meshCol) {
  37747. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  37748. }
  37749. fi++;
  37750. }
  37751. // create a model shape for each single particle
  37752. var idx = this.nbParticles;
  37753. var shape = this._posToShape(facetPos);
  37754. var shapeUV = this._uvsToShapeUV(facetUV);
  37755. // compute the barycenter of the shape
  37756. var v;
  37757. for (v = 0; v < shape.length; v++) {
  37758. barycenter.addInPlace(shape[v]);
  37759. }
  37760. barycenter.scaleInPlace(1 / shape.length);
  37761. // shift the shape from its barycenter to the origin
  37762. for (v = 0; v < shape.length; v++) {
  37763. shape[v].subtractInPlace(barycenter);
  37764. }
  37765. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  37766. // add the particle in the SPS
  37767. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  37768. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  37769. // initialize the particle position
  37770. this.particles[this.nbParticles].position.addInPlace(barycenter);
  37771. this._index += shape.length;
  37772. idx++;
  37773. this.nbParticles++;
  37774. this._shapeCounter++;
  37775. f += size;
  37776. }
  37777. };
  37778. //reset copy
  37779. SolidParticleSystem.prototype._resetCopy = function () {
  37780. this._copy.position.x = 0;
  37781. this._copy.position.y = 0;
  37782. this._copy.position.z = 0;
  37783. this._copy.rotation.x = 0;
  37784. this._copy.rotation.y = 0;
  37785. this._copy.rotation.z = 0;
  37786. this._copy.quaternion = null;
  37787. this._copy.scale.x = 1;
  37788. this._copy.scale.y = 1;
  37789. this._copy.scale.z = 1;
  37790. this._copy.uvs.x = 0;
  37791. this._copy.uvs.y = 0;
  37792. this._copy.uvs.z = 1;
  37793. this._copy.uvs.w = 1;
  37794. this._copy.color = null;
  37795. };
  37796. // _meshBuilder : inserts the shape model in the global SPS mesh
  37797. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  37798. var i;
  37799. var u = 0;
  37800. var c = 0;
  37801. this._resetCopy();
  37802. if (options && options.positionFunction) {
  37803. options.positionFunction(this._copy, idx, idxInShape);
  37804. }
  37805. if (this._copy.quaternion) {
  37806. this._quaternion.x = this._copy.quaternion.x;
  37807. this._quaternion.y = this._copy.quaternion.y;
  37808. this._quaternion.z = this._copy.quaternion.z;
  37809. this._quaternion.w = this._copy.quaternion.w;
  37810. }
  37811. else {
  37812. this._yaw = this._copy.rotation.y;
  37813. this._pitch = this._copy.rotation.x;
  37814. this._roll = this._copy.rotation.z;
  37815. this._quaternionRotationYPR();
  37816. }
  37817. this._quaternionToRotationMatrix();
  37818. for (i = 0; i < shape.length; i++) {
  37819. this._vertex.x = shape[i].x;
  37820. this._vertex.y = shape[i].y;
  37821. this._vertex.z = shape[i].z;
  37822. if (options && options.vertexFunction) {
  37823. options.vertexFunction(this._copy, this._vertex, i);
  37824. }
  37825. this._vertex.x *= this._copy.scale.x;
  37826. this._vertex.y *= this._copy.scale.y;
  37827. this._vertex.z *= this._copy.scale.z;
  37828. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37829. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  37830. if (meshUV) {
  37831. 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);
  37832. u += 2;
  37833. }
  37834. if (this._copy.color) {
  37835. this._color = this._copy.color;
  37836. }
  37837. else if (meshCol && meshCol[c]) {
  37838. this._color.r = meshCol[c];
  37839. this._color.g = meshCol[c + 1];
  37840. this._color.b = meshCol[c + 2];
  37841. this._color.a = meshCol[c + 3];
  37842. }
  37843. else {
  37844. this._color.r = 1;
  37845. this._color.g = 1;
  37846. this._color.b = 1;
  37847. this._color.a = 1;
  37848. }
  37849. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  37850. c += 4;
  37851. }
  37852. for (i = 0; i < meshInd.length; i++) {
  37853. indices.push(p + meshInd[i]);
  37854. }
  37855. if (this._pickable) {
  37856. var nbfaces = meshInd.length / 3;
  37857. for (i = 0; i < nbfaces; i++) {
  37858. this.pickedParticles.push({ idx: idx, faceId: i });
  37859. }
  37860. }
  37861. };
  37862. // returns a shape array from positions array
  37863. SolidParticleSystem.prototype._posToShape = function (positions) {
  37864. var shape = [];
  37865. for (var i = 0; i < positions.length; i += 3) {
  37866. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  37867. }
  37868. return shape;
  37869. };
  37870. // returns a shapeUV array from a Vector4 uvs
  37871. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37872. var shapeUV = [];
  37873. if (uvs) {
  37874. for (var i = 0; i < uvs.length; i++)
  37875. shapeUV.push(uvs[i]);
  37876. }
  37877. return shapeUV;
  37878. };
  37879. // adds a new particle object in the particles array
  37880. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  37881. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  37882. };
  37883. /**
  37884. * Adds some particles to the SPS from the model shape.
  37885. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  37886. * @param mesh any Mesh object that will be used as a model for the solid particles.
  37887. * @param nb the number of particles to be created from this model
  37888. * @param options positionFunction is an optional javascript function to called for each particle on SPS creation. vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  37889. */
  37890. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37891. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37892. var meshInd = mesh.getIndices();
  37893. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37894. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37895. var shape = this._posToShape(meshPos);
  37896. var shapeUV = this._uvsToShapeUV(meshUV);
  37897. var posfunc = options ? options.positionFunction : null;
  37898. var vtxfunc = options ? options.vertexFunction : null;
  37899. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37900. // particles
  37901. var idx = this.nbParticles;
  37902. for (var i = 0; i < nb; i++) {
  37903. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  37904. if (this._updatable) {
  37905. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  37906. }
  37907. this._index += shape.length;
  37908. idx++;
  37909. }
  37910. this.nbParticles += nb;
  37911. this._shapeCounter++;
  37912. return this._shapeCounter - 1;
  37913. };
  37914. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37915. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37916. this._resetCopy();
  37917. if (particle._model._positionFunction) {
  37918. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37919. }
  37920. if (this._copy.quaternion) {
  37921. this._quaternion.x = this._copy.quaternion.x;
  37922. this._quaternion.y = this._copy.quaternion.y;
  37923. this._quaternion.z = this._copy.quaternion.z;
  37924. this._quaternion.w = this._copy.quaternion.w;
  37925. }
  37926. else {
  37927. this._yaw = this._copy.rotation.y;
  37928. this._pitch = this._copy.rotation.x;
  37929. this._roll = this._copy.rotation.z;
  37930. this._quaternionRotationYPR();
  37931. }
  37932. this._quaternionToRotationMatrix();
  37933. this._shape = particle._model._shape;
  37934. for (var pt = 0; pt < this._shape.length; pt++) {
  37935. this._vertex.x = this._shape[pt].x;
  37936. this._vertex.y = this._shape[pt].y;
  37937. this._vertex.z = this._shape[pt].z;
  37938. if (particle._model._vertexFunction) {
  37939. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37940. }
  37941. this._vertex.x *= this._copy.scale.x;
  37942. this._vertex.y *= this._copy.scale.y;
  37943. this._vertex.z *= this._copy.scale.z;
  37944. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37945. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37946. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37947. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37948. }
  37949. particle.position.x = 0;
  37950. particle.position.y = 0;
  37951. particle.position.z = 0;
  37952. particle.rotation.x = 0;
  37953. particle.rotation.y = 0;
  37954. particle.rotation.z = 0;
  37955. particle.quaternion = null;
  37956. particle.scale.x = 1;
  37957. particle.scale.y = 1;
  37958. particle.scale.z = 1;
  37959. };
  37960. /**
  37961. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37962. */
  37963. SolidParticleSystem.prototype.rebuildMesh = function () {
  37964. for (var p = 0; p < this.particles.length; p++) {
  37965. this._rebuildParticle(this.particles[p]);
  37966. }
  37967. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37968. };
  37969. /**
  37970. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37971. * This method calls updateParticle() for each particles of the SPS.
  37972. * For an animated SPS, it is usually called within the render loop.
  37973. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  37974. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  37975. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  37976. */
  37977. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37978. if (start === void 0) { start = 0; }
  37979. if (end === void 0) { end = this.nbParticles - 1; }
  37980. if (update === void 0) { update = true; }
  37981. if (!this._updatable) {
  37982. return;
  37983. }
  37984. // custom beforeUpdate
  37985. this.beforeUpdateParticles(start, end, update);
  37986. this._cam_axisX.x = 1;
  37987. this._cam_axisX.y = 0;
  37988. this._cam_axisX.z = 0;
  37989. this._cam_axisY.x = 0;
  37990. this._cam_axisY.y = 1;
  37991. this._cam_axisY.z = 0;
  37992. this._cam_axisZ.x = 0;
  37993. this._cam_axisZ.y = 0;
  37994. this._cam_axisZ.z = 1;
  37995. // if the particles will always face the camera
  37996. if (this.billboard) {
  37997. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  37998. this._yaw = this.mesh.rotation.y;
  37999. this._pitch = this.mesh.rotation.x;
  38000. this._roll = this.mesh.rotation.z;
  38001. this._quaternionRotationYPR();
  38002. this._quaternionToRotationMatrix();
  38003. this._rotMatrix.invertToRef(this._invertMatrix);
  38004. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  38005. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  38006. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  38007. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  38008. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  38009. this._cam_axisY.normalize();
  38010. this._cam_axisX.normalize();
  38011. this._cam_axisZ.normalize();
  38012. }
  38013. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38014. var idx = 0;
  38015. var index = 0;
  38016. var colidx = 0;
  38017. var colorIndex = 0;
  38018. var uvidx = 0;
  38019. var uvIndex = 0;
  38020. if (this._computeBoundingBox) {
  38021. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38022. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38023. }
  38024. // particle loop
  38025. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  38026. for (var p = start; p <= end; p++) {
  38027. this._particle = this.particles[p];
  38028. this._shape = this._particle._model._shape;
  38029. this._shapeUV = this._particle._model._shapeUV;
  38030. // call to custom user function to update the particle properties
  38031. this.updateParticle(this._particle);
  38032. // particle rotation matrix
  38033. if (this.billboard) {
  38034. this._particle.rotation.x = 0.0;
  38035. this._particle.rotation.y = 0.0;
  38036. }
  38037. if (this._computeParticleRotation) {
  38038. if (this._particle.quaternion) {
  38039. this._quaternion.x = this._particle.quaternion.x;
  38040. this._quaternion.y = this._particle.quaternion.y;
  38041. this._quaternion.z = this._particle.quaternion.z;
  38042. this._quaternion.w = this._particle.quaternion.w;
  38043. }
  38044. else {
  38045. this._yaw = this._particle.rotation.y;
  38046. this._pitch = this._particle.rotation.x;
  38047. this._roll = this._particle.rotation.z;
  38048. this._quaternionRotationYPR();
  38049. }
  38050. this._quaternionToRotationMatrix();
  38051. }
  38052. for (var pt = 0; pt < this._shape.length; pt++) {
  38053. idx = index + pt * 3;
  38054. colidx = colorIndex + pt * 4;
  38055. uvidx = uvIndex + pt * 2;
  38056. this._vertex.x = this._shape[pt].x;
  38057. this._vertex.y = this._shape[pt].y;
  38058. this._vertex.z = this._shape[pt].z;
  38059. if (this._computeParticleVertex) {
  38060. this.updateParticleVertex(this._particle, this._vertex, pt);
  38061. }
  38062. // positions
  38063. this._vertex.x *= this._particle.scale.x;
  38064. this._vertex.y *= this._particle.scale.y;
  38065. this._vertex.z *= this._particle.scale.z;
  38066. 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];
  38067. 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;
  38068. 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;
  38069. 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;
  38070. 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;
  38071. 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;
  38072. 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;
  38073. if (this._computeBoundingBox) {
  38074. if (this._positions32[idx] < this._minimum.x) {
  38075. this._minimum.x = this._positions32[idx];
  38076. }
  38077. if (this._positions32[idx] > this._maximum.x) {
  38078. this._maximum.x = this._positions32[idx];
  38079. }
  38080. if (this._positions32[idx + 1] < this._minimum.y) {
  38081. this._minimum.y = this._positions32[idx + 1];
  38082. }
  38083. if (this._positions32[idx + 1] > this._maximum.y) {
  38084. this._maximum.y = this._positions32[idx + 1];
  38085. }
  38086. if (this._positions32[idx + 2] < this._minimum.z) {
  38087. this._minimum.z = this._positions32[idx + 2];
  38088. }
  38089. if (this._positions32[idx + 2] > this._maximum.z) {
  38090. this._maximum.z = this._positions32[idx + 2];
  38091. }
  38092. }
  38093. // normals : if the particles can't be morphed then just rotate the normals
  38094. if (!this._computeParticleVertex && !this.billboard) {
  38095. this._normal.x = this._fixedNormal32[idx];
  38096. this._normal.y = this._fixedNormal32[idx + 1];
  38097. this._normal.z = this._fixedNormal32[idx + 2];
  38098. 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];
  38099. 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;
  38100. 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;
  38101. 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;
  38102. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38103. 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;
  38104. 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;
  38105. }
  38106. if (this._computeParticleColor) {
  38107. this._colors32[colidx] = this._particle.color.r;
  38108. this._colors32[colidx + 1] = this._particle.color.g;
  38109. this._colors32[colidx + 2] = this._particle.color.b;
  38110. this._colors32[colidx + 3] = this._particle.color.a;
  38111. }
  38112. if (this._computeParticleTexture) {
  38113. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38114. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38115. }
  38116. }
  38117. index = idx + 3;
  38118. colorIndex = colidx + 4;
  38119. uvIndex = uvidx + 2;
  38120. }
  38121. if (update) {
  38122. if (this._computeParticleColor) {
  38123. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  38124. }
  38125. if (this._computeParticleTexture) {
  38126. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  38127. }
  38128. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38129. if (!this.mesh.areNormalsFrozen) {
  38130. if (this._computeParticleVertex || this.billboard) {
  38131. // recompute the normals only if the particles can be morphed, update then the normal reference array
  38132. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  38133. for (var i = 0; i < this._normals32.length; i++) {
  38134. this._fixedNormal32[i] = this._normals32[i];
  38135. }
  38136. }
  38137. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  38138. }
  38139. }
  38140. if (this._computeBoundingBox) {
  38141. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  38142. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  38143. }
  38144. this.afterUpdateParticles(start, end, update);
  38145. };
  38146. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  38147. this._halfroll = this._roll * 0.5;
  38148. this._halfpitch = this._pitch * 0.5;
  38149. this._halfyaw = this._yaw * 0.5;
  38150. this._sinRoll = Math.sin(this._halfroll);
  38151. this._cosRoll = Math.cos(this._halfroll);
  38152. this._sinPitch = Math.sin(this._halfpitch);
  38153. this._cosPitch = Math.cos(this._halfpitch);
  38154. this._sinYaw = Math.sin(this._halfyaw);
  38155. this._cosYaw = Math.cos(this._halfyaw);
  38156. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  38157. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  38158. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  38159. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  38160. };
  38161. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  38162. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  38163. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  38164. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  38165. this._rotMatrix.m[3] = 0;
  38166. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  38167. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  38168. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  38169. this._rotMatrix.m[7] = 0;
  38170. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  38171. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  38172. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  38173. this._rotMatrix.m[11] = 0;
  38174. this._rotMatrix.m[12] = 0;
  38175. this._rotMatrix.m[13] = 0;
  38176. this._rotMatrix.m[14] = 0;
  38177. this._rotMatrix.m[15] = 1.0;
  38178. };
  38179. /**
  38180. * Disposes the SPS
  38181. */
  38182. SolidParticleSystem.prototype.dispose = function () {
  38183. this.mesh.dispose();
  38184. this.vars = null;
  38185. // drop references to internal big arrays for the GC
  38186. this._positions = null;
  38187. this._indices = null;
  38188. this._normals = null;
  38189. this._uvs = null;
  38190. this._colors = null;
  38191. this._positions32 = null;
  38192. this._normals32 = null;
  38193. this._fixedNormal32 = null;
  38194. this._uvs32 = null;
  38195. this._colors32 = null;
  38196. this.pickedParticles = null;
  38197. };
  38198. /**
  38199. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  38200. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38201. */
  38202. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  38203. if (!this._isVisibilityBoxLocked) {
  38204. this.mesh.refreshBoundingInfo();
  38205. }
  38206. };
  38207. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  38208. * @param size the size (float) of the visibility box
  38209. * note : this doesn't lock the SPS mesh bounding box.
  38210. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38211. */
  38212. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  38213. var vis = size / 2;
  38214. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  38215. };
  38216. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  38217. // getter and setter
  38218. /**
  38219. * True if the SPS is set as always visible
  38220. */
  38221. get: function () {
  38222. return this._alwaysVisible;
  38223. },
  38224. /**
  38225. * Sets the SPS as always visible or not
  38226. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38227. */
  38228. set: function (val) {
  38229. this._alwaysVisible = val;
  38230. this.mesh.alwaysSelectAsActiveMesh = val;
  38231. },
  38232. enumerable: true,
  38233. configurable: true
  38234. });
  38235. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  38236. /**
  38237. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  38238. */
  38239. get: function () {
  38240. return this._isVisibilityBoxLocked;
  38241. },
  38242. /**
  38243. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  38244. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38245. */
  38246. set: function (val) {
  38247. this._isVisibilityBoxLocked = val;
  38248. this.mesh.getBoundingInfo().isLocked = val;
  38249. },
  38250. enumerable: true,
  38251. configurable: true
  38252. });
  38253. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  38254. // getters
  38255. get: function () {
  38256. return this._computeParticleRotation;
  38257. },
  38258. // Optimizer setters
  38259. /**
  38260. * Tells to setParticles() to compute the particle rotations or not.
  38261. * Default value : true. The SPS is faster when it's set to false.
  38262. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  38263. */
  38264. set: function (val) {
  38265. this._computeParticleRotation = val;
  38266. },
  38267. enumerable: true,
  38268. configurable: true
  38269. });
  38270. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  38271. get: function () {
  38272. return this._computeParticleColor;
  38273. },
  38274. /**
  38275. * Tells to setParticles() to compute the particle colors or not.
  38276. * Default value : true. The SPS is faster when it's set to false.
  38277. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  38278. */
  38279. set: function (val) {
  38280. this._computeParticleColor = val;
  38281. },
  38282. enumerable: true,
  38283. configurable: true
  38284. });
  38285. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  38286. get: function () {
  38287. return this._computeParticleTexture;
  38288. },
  38289. /**
  38290. * Tells to setParticles() to compute the particle textures or not.
  38291. * Default value : true. The SPS is faster when it's set to false.
  38292. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  38293. */
  38294. set: function (val) {
  38295. this._computeParticleTexture = val;
  38296. },
  38297. enumerable: true,
  38298. configurable: true
  38299. });
  38300. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  38301. get: function () {
  38302. return this._computeParticleVertex;
  38303. },
  38304. /**
  38305. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  38306. * Default value : false. The SPS is faster when it's set to false.
  38307. * Note : the particle custom vertex positions aren't stored values.
  38308. */
  38309. set: function (val) {
  38310. this._computeParticleVertex = val;
  38311. },
  38312. enumerable: true,
  38313. configurable: true
  38314. });
  38315. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  38316. get: function () {
  38317. return this._computeBoundingBox;
  38318. },
  38319. /**
  38320. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  38321. */
  38322. set: function (val) {
  38323. this._computeBoundingBox = val;
  38324. },
  38325. enumerable: true,
  38326. configurable: true
  38327. });
  38328. // =======================================================================
  38329. // Particle behavior logic
  38330. // these following methods may be overwritten by the user to fit his needs
  38331. /**
  38332. * This function does nothing. It may be overwritten to set all the particles first values.
  38333. * The SPS doesn't call this function, you may have to call it by your own.
  38334. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38335. */
  38336. SolidParticleSystem.prototype.initParticles = function () {
  38337. };
  38338. /**
  38339. * This function does nothing. It may be overwritten to recycle a particle.
  38340. * The SPS doesn't call this function, you may have to call it by your own.
  38341. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38342. */
  38343. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  38344. return particle;
  38345. };
  38346. /**
  38347. * Updates a particle : this function should be overwritten by the user.
  38348. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  38349. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38350. * ex : just set a particle position or velocity and recycle conditions
  38351. */
  38352. SolidParticleSystem.prototype.updateParticle = function (particle) {
  38353. return particle;
  38354. };
  38355. /**
  38356. * Updates a vertex of a particle : it can be overwritten by the user.
  38357. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  38358. * @param particle the current particle
  38359. * @param vertex the current index of the current particle
  38360. * @param pt the index of the current vertex in the particle shape
  38361. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  38362. * ex : just set a vertex particle position
  38363. */
  38364. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  38365. return vertex;
  38366. };
  38367. /**
  38368. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  38369. * This does nothing and may be overwritten by the user.
  38370. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38371. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38372. * @param update the boolean update value actually passed to setParticles()
  38373. */
  38374. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  38375. };
  38376. /**
  38377. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  38378. * This will be passed three parameters.
  38379. * This does nothing and may be overwritten by the user.
  38380. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38381. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38382. * @param update the boolean update value actually passed to setParticles()
  38383. */
  38384. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  38385. };
  38386. return SolidParticleSystem;
  38387. })();
  38388. BABYLON.SolidParticleSystem = SolidParticleSystem;
  38389. })(BABYLON || (BABYLON = {}));
  38390. var BABYLON;
  38391. (function (BABYLON) {
  38392. // We're mainly based on the logic defined into the FreeCamera code
  38393. var UniversalCamera = (function (_super) {
  38394. __extends(UniversalCamera, _super);
  38395. function UniversalCamera(name, position, scene) {
  38396. var _this = this;
  38397. _super.call(this, name, position, scene);
  38398. this.gamepadAngularSensibility = 200;
  38399. this.gamepadMoveSensibility = 40;
  38400. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  38401. }
  38402. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  38403. // Only the first gamepad can control the camera
  38404. if (gamepad.index === 0) {
  38405. this.gamepad = gamepad;
  38406. }
  38407. };
  38408. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  38409. _super.prototype.attachControl.call(this, canvas, false);
  38410. };
  38411. UniversalCamera.prototype.detachControl = function (canvas) {
  38412. _super.prototype.detachControl.call(this, canvas);
  38413. };
  38414. UniversalCamera.prototype._checkInputs = function () {
  38415. if (this.gamepad) {
  38416. var LSValues = this.gamepad.leftStick;
  38417. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  38418. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  38419. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  38420. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  38421. var RSValues = this.gamepad.rightStick;
  38422. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  38423. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  38424. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  38425. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  38426. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  38427. var speed = this._computeLocalCameraSpeed() * 50.0;
  38428. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  38429. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  38430. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  38431. }
  38432. _super.prototype._checkInputs.call(this);
  38433. };
  38434. UniversalCamera.prototype.dispose = function () {
  38435. this._gamepads.dispose();
  38436. _super.prototype.dispose.call(this);
  38437. };
  38438. UniversalCamera.prototype.getTypeName = function () {
  38439. return "UniversalCamera";
  38440. };
  38441. __decorate([
  38442. BABYLON.serialize()
  38443. ], UniversalCamera.prototype, "gamepadAngularSensibility", void 0);
  38444. __decorate([
  38445. BABYLON.serialize()
  38446. ], UniversalCamera.prototype, "gamepadMoveSensibility", void 0);
  38447. return UniversalCamera;
  38448. })(BABYLON.TouchCamera);
  38449. BABYLON.UniversalCamera = UniversalCamera;
  38450. })(BABYLON || (BABYLON = {}));
  38451. var BABYLON;
  38452. (function (BABYLON) {
  38453. var Gamepads = (function () {
  38454. function Gamepads(ongamedpadconnected) {
  38455. var _this = this;
  38456. this.babylonGamepads = [];
  38457. this.oneGamepadConnected = false;
  38458. this.isMonitoring = false;
  38459. this.gamepadEventSupported = 'GamepadEvent' in window;
  38460. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38461. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38462. this._callbackGamepadConnected = ongamedpadconnected;
  38463. if (this.gamepadSupportAvailable) {
  38464. // Checking if the gamepad connected event is supported (like in Firefox)
  38465. if (this.gamepadEventSupported) {
  38466. window.addEventListener('gamepadconnected', function (evt) {
  38467. _this._onGamepadConnected(evt);
  38468. }, false);
  38469. window.addEventListener('gamepaddisconnected', function (evt) {
  38470. _this._onGamepadDisconnected(evt);
  38471. }, false);
  38472. }
  38473. else {
  38474. this._startMonitoringGamepads();
  38475. }
  38476. }
  38477. }
  38478. Gamepads.prototype.dispose = function () {
  38479. if (Gamepads.gamepadDOMInfo) {
  38480. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38481. }
  38482. };
  38483. Gamepads.prototype._onGamepadConnected = function (evt) {
  38484. var newGamepad = this._addNewGamepad(evt.gamepad);
  38485. if (this._callbackGamepadConnected)
  38486. this._callbackGamepadConnected(newGamepad);
  38487. this._startMonitoringGamepads();
  38488. };
  38489. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38490. if (!this.oneGamepadConnected) {
  38491. this.oneGamepadConnected = true;
  38492. if (Gamepads.gamepadDOMInfo) {
  38493. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38494. Gamepads.gamepadDOMInfo = null;
  38495. }
  38496. }
  38497. var newGamepad;
  38498. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38499. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38500. }
  38501. else {
  38502. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38503. }
  38504. this.babylonGamepads.push(newGamepad);
  38505. return newGamepad;
  38506. };
  38507. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38508. // Remove the gamepad from the list of gamepads to monitor.
  38509. for (var i in this.babylonGamepads) {
  38510. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38511. this.babylonGamepads.splice(+i, 1);
  38512. break;
  38513. }
  38514. }
  38515. // If no gamepads are left, stop the polling loop.
  38516. if (this.babylonGamepads.length == 0) {
  38517. this._stopMonitoringGamepads();
  38518. }
  38519. };
  38520. Gamepads.prototype._startMonitoringGamepads = function () {
  38521. if (!this.isMonitoring) {
  38522. this.isMonitoring = true;
  38523. this._checkGamepadsStatus();
  38524. }
  38525. };
  38526. Gamepads.prototype._stopMonitoringGamepads = function () {
  38527. this.isMonitoring = false;
  38528. };
  38529. Gamepads.prototype._checkGamepadsStatus = function () {
  38530. var _this = this;
  38531. // updating gamepad objects
  38532. this._updateGamepadObjects();
  38533. for (var i in this.babylonGamepads) {
  38534. this.babylonGamepads[i].update();
  38535. }
  38536. if (this.isMonitoring) {
  38537. if (window.requestAnimationFrame) {
  38538. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38539. }
  38540. else if (window.mozRequestAnimationFrame) {
  38541. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38542. }
  38543. else if (window.webkitRequestAnimationFrame) {
  38544. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38545. }
  38546. }
  38547. };
  38548. // This function is called only on Chrome, which does not yet support
  38549. // connection/disconnection events, but requires you to monitor
  38550. // an array for changes.
  38551. Gamepads.prototype._updateGamepadObjects = function () {
  38552. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  38553. for (var i = 0; i < gamepads.length; i++) {
  38554. if (gamepads[i]) {
  38555. if (!(gamepads[i].index in this.babylonGamepads)) {
  38556. var newGamepad = this._addNewGamepad(gamepads[i]);
  38557. if (this._callbackGamepadConnected) {
  38558. this._callbackGamepadConnected(newGamepad);
  38559. }
  38560. }
  38561. else {
  38562. this.babylonGamepads[i].browserGamepad = gamepads[i];
  38563. }
  38564. }
  38565. }
  38566. };
  38567. return Gamepads;
  38568. })();
  38569. BABYLON.Gamepads = Gamepads;
  38570. var StickValues = (function () {
  38571. function StickValues(x, y) {
  38572. this.x = x;
  38573. this.y = y;
  38574. }
  38575. return StickValues;
  38576. })();
  38577. BABYLON.StickValues = StickValues;
  38578. var Gamepad = (function () {
  38579. function Gamepad(id, index, browserGamepad) {
  38580. this.id = id;
  38581. this.index = index;
  38582. this.browserGamepad = browserGamepad;
  38583. if (this.browserGamepad.axes.length >= 2) {
  38584. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38585. }
  38586. if (this.browserGamepad.axes.length >= 4) {
  38587. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38588. }
  38589. }
  38590. Gamepad.prototype.onleftstickchanged = function (callback) {
  38591. this._onleftstickchanged = callback;
  38592. };
  38593. Gamepad.prototype.onrightstickchanged = function (callback) {
  38594. this._onrightstickchanged = callback;
  38595. };
  38596. Object.defineProperty(Gamepad.prototype, "leftStick", {
  38597. get: function () {
  38598. return this._leftStick;
  38599. },
  38600. set: function (newValues) {
  38601. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  38602. this._onleftstickchanged(newValues);
  38603. }
  38604. this._leftStick = newValues;
  38605. },
  38606. enumerable: true,
  38607. configurable: true
  38608. });
  38609. Object.defineProperty(Gamepad.prototype, "rightStick", {
  38610. get: function () {
  38611. return this._rightStick;
  38612. },
  38613. set: function (newValues) {
  38614. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  38615. this._onrightstickchanged(newValues);
  38616. }
  38617. this._rightStick = newValues;
  38618. },
  38619. enumerable: true,
  38620. configurable: true
  38621. });
  38622. Gamepad.prototype.update = function () {
  38623. if (this._leftStick) {
  38624. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38625. }
  38626. if (this._rightStick) {
  38627. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38628. }
  38629. };
  38630. return Gamepad;
  38631. })();
  38632. BABYLON.Gamepad = Gamepad;
  38633. var GenericPad = (function (_super) {
  38634. __extends(GenericPad, _super);
  38635. function GenericPad(id, index, gamepad) {
  38636. _super.call(this, id, index, gamepad);
  38637. this.id = id;
  38638. this.index = index;
  38639. this.gamepad = gamepad;
  38640. this._buttons = new Array(gamepad.buttons.length);
  38641. }
  38642. GenericPad.prototype.onbuttondown = function (callback) {
  38643. this._onbuttondown = callback;
  38644. };
  38645. GenericPad.prototype.onbuttonup = function (callback) {
  38646. this._onbuttonup = callback;
  38647. };
  38648. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  38649. if (newValue !== currentValue) {
  38650. if (this._onbuttondown && newValue === 1) {
  38651. this._onbuttondown(buttonIndex);
  38652. }
  38653. if (this._onbuttonup && newValue === 0) {
  38654. this._onbuttonup(buttonIndex);
  38655. }
  38656. }
  38657. return newValue;
  38658. };
  38659. GenericPad.prototype.update = function () {
  38660. _super.prototype.update.call(this);
  38661. for (var index = 0; index < this._buttons.length; index++) {
  38662. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  38663. }
  38664. };
  38665. return GenericPad;
  38666. })(Gamepad);
  38667. BABYLON.GenericPad = GenericPad;
  38668. (function (Xbox360Button) {
  38669. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  38670. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  38671. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  38672. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  38673. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  38674. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  38675. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  38676. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  38677. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  38678. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  38679. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  38680. var Xbox360Button = BABYLON.Xbox360Button;
  38681. (function (Xbox360Dpad) {
  38682. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  38683. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  38684. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  38685. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  38686. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  38687. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  38688. var Xbox360Pad = (function (_super) {
  38689. __extends(Xbox360Pad, _super);
  38690. function Xbox360Pad() {
  38691. _super.apply(this, arguments);
  38692. this._leftTrigger = 0;
  38693. this._rightTrigger = 0;
  38694. this._buttonA = 0;
  38695. this._buttonB = 0;
  38696. this._buttonX = 0;
  38697. this._buttonY = 0;
  38698. this._buttonBack = 0;
  38699. this._buttonStart = 0;
  38700. this._buttonLB = 0;
  38701. this._buttonRB = 0;
  38702. this._buttonLeftStick = 0;
  38703. this._buttonRightStick = 0;
  38704. this._dPadUp = 0;
  38705. this._dPadDown = 0;
  38706. this._dPadLeft = 0;
  38707. this._dPadRight = 0;
  38708. }
  38709. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  38710. this._onlefttriggerchanged = callback;
  38711. };
  38712. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  38713. this._onrighttriggerchanged = callback;
  38714. };
  38715. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  38716. get: function () {
  38717. return this._leftTrigger;
  38718. },
  38719. set: function (newValue) {
  38720. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  38721. this._onlefttriggerchanged(newValue);
  38722. }
  38723. this._leftTrigger = newValue;
  38724. },
  38725. enumerable: true,
  38726. configurable: true
  38727. });
  38728. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  38729. get: function () {
  38730. return this._rightTrigger;
  38731. },
  38732. set: function (newValue) {
  38733. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  38734. this._onrighttriggerchanged(newValue);
  38735. }
  38736. this._rightTrigger = newValue;
  38737. },
  38738. enumerable: true,
  38739. configurable: true
  38740. });
  38741. Xbox360Pad.prototype.onbuttondown = function (callback) {
  38742. this._onbuttondown = callback;
  38743. };
  38744. Xbox360Pad.prototype.onbuttonup = function (callback) {
  38745. this._onbuttonup = callback;
  38746. };
  38747. Xbox360Pad.prototype.ondpaddown = function (callback) {
  38748. this._ondpaddown = callback;
  38749. };
  38750. Xbox360Pad.prototype.ondpadup = function (callback) {
  38751. this._ondpadup = callback;
  38752. };
  38753. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  38754. if (newValue !== currentValue) {
  38755. if (this._onbuttondown && newValue === 1) {
  38756. this._onbuttondown(buttonType);
  38757. }
  38758. if (this._onbuttonup && newValue === 0) {
  38759. this._onbuttonup(buttonType);
  38760. }
  38761. }
  38762. return newValue;
  38763. };
  38764. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  38765. if (newValue !== currentValue) {
  38766. if (this._ondpaddown && newValue === 1) {
  38767. this._ondpaddown(buttonType);
  38768. }
  38769. if (this._ondpadup && newValue === 0) {
  38770. this._ondpadup(buttonType);
  38771. }
  38772. }
  38773. return newValue;
  38774. };
  38775. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  38776. get: function () {
  38777. return this._buttonA;
  38778. },
  38779. set: function (value) {
  38780. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  38781. },
  38782. enumerable: true,
  38783. configurable: true
  38784. });
  38785. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  38786. get: function () {
  38787. return this._buttonB;
  38788. },
  38789. set: function (value) {
  38790. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  38791. },
  38792. enumerable: true,
  38793. configurable: true
  38794. });
  38795. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  38796. get: function () {
  38797. return this._buttonX;
  38798. },
  38799. set: function (value) {
  38800. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  38801. },
  38802. enumerable: true,
  38803. configurable: true
  38804. });
  38805. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  38806. get: function () {
  38807. return this._buttonY;
  38808. },
  38809. set: function (value) {
  38810. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  38811. },
  38812. enumerable: true,
  38813. configurable: true
  38814. });
  38815. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  38816. get: function () {
  38817. return this._buttonStart;
  38818. },
  38819. set: function (value) {
  38820. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  38821. },
  38822. enumerable: true,
  38823. configurable: true
  38824. });
  38825. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  38826. get: function () {
  38827. return this._buttonBack;
  38828. },
  38829. set: function (value) {
  38830. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  38831. },
  38832. enumerable: true,
  38833. configurable: true
  38834. });
  38835. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  38836. get: function () {
  38837. return this._buttonLB;
  38838. },
  38839. set: function (value) {
  38840. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  38841. },
  38842. enumerable: true,
  38843. configurable: true
  38844. });
  38845. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  38846. get: function () {
  38847. return this._buttonRB;
  38848. },
  38849. set: function (value) {
  38850. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  38851. },
  38852. enumerable: true,
  38853. configurable: true
  38854. });
  38855. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  38856. get: function () {
  38857. return this._buttonLeftStick;
  38858. },
  38859. set: function (value) {
  38860. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  38861. },
  38862. enumerable: true,
  38863. configurable: true
  38864. });
  38865. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  38866. get: function () {
  38867. return this._buttonRightStick;
  38868. },
  38869. set: function (value) {
  38870. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  38871. },
  38872. enumerable: true,
  38873. configurable: true
  38874. });
  38875. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  38876. get: function () {
  38877. return this._dPadUp;
  38878. },
  38879. set: function (value) {
  38880. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  38881. },
  38882. enumerable: true,
  38883. configurable: true
  38884. });
  38885. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  38886. get: function () {
  38887. return this._dPadDown;
  38888. },
  38889. set: function (value) {
  38890. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  38891. },
  38892. enumerable: true,
  38893. configurable: true
  38894. });
  38895. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  38896. get: function () {
  38897. return this._dPadLeft;
  38898. },
  38899. set: function (value) {
  38900. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  38901. },
  38902. enumerable: true,
  38903. configurable: true
  38904. });
  38905. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  38906. get: function () {
  38907. return this._dPadRight;
  38908. },
  38909. set: function (value) {
  38910. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  38911. },
  38912. enumerable: true,
  38913. configurable: true
  38914. });
  38915. Xbox360Pad.prototype.update = function () {
  38916. _super.prototype.update.call(this);
  38917. this.buttonA = this.browserGamepad.buttons[0].value;
  38918. this.buttonB = this.browserGamepad.buttons[1].value;
  38919. this.buttonX = this.browserGamepad.buttons[2].value;
  38920. this.buttonY = this.browserGamepad.buttons[3].value;
  38921. this.buttonLB = this.browserGamepad.buttons[4].value;
  38922. this.buttonRB = this.browserGamepad.buttons[5].value;
  38923. this.leftTrigger = this.browserGamepad.buttons[6].value;
  38924. this.rightTrigger = this.browserGamepad.buttons[7].value;
  38925. this.buttonBack = this.browserGamepad.buttons[8].value;
  38926. this.buttonStart = this.browserGamepad.buttons[9].value;
  38927. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  38928. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  38929. this.dPadUp = this.browserGamepad.buttons[12].value;
  38930. this.dPadDown = this.browserGamepad.buttons[13].value;
  38931. this.dPadLeft = this.browserGamepad.buttons[14].value;
  38932. this.dPadRight = this.browserGamepad.buttons[15].value;
  38933. };
  38934. return Xbox360Pad;
  38935. })(Gamepad);
  38936. BABYLON.Xbox360Pad = Xbox360Pad;
  38937. })(BABYLON || (BABYLON = {}));
  38938. var BABYLON;
  38939. (function (BABYLON) {
  38940. // We're mainly based on the logic defined into the FreeCamera code
  38941. var GamepadCamera = (function (_super) {
  38942. __extends(GamepadCamera, _super);
  38943. function GamepadCamera(name, position, scene) {
  38944. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  38945. _super.call(this, name, position, scene);
  38946. }
  38947. GamepadCamera.prototype.getTypeName = function () {
  38948. return "GamepadCamera";
  38949. };
  38950. return GamepadCamera;
  38951. })(BABYLON.UniversalCamera);
  38952. BABYLON.GamepadCamera = GamepadCamera;
  38953. })(BABYLON || (BABYLON = {}));
  38954. var BABYLON;
  38955. (function (BABYLON) {
  38956. var AnaglyphFreeCamera = (function (_super) {
  38957. __extends(AnaglyphFreeCamera, _super);
  38958. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  38959. _super.call(this, name, position, scene);
  38960. this.interaxialDistance = interaxialDistance;
  38961. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38962. }
  38963. AnaglyphFreeCamera.prototype.getTypeName = function () {
  38964. return "AnaglyphFreeCamera";
  38965. };
  38966. return AnaglyphFreeCamera;
  38967. })(BABYLON.FreeCamera);
  38968. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  38969. var AnaglyphArcRotateCamera = (function (_super) {
  38970. __extends(AnaglyphArcRotateCamera, _super);
  38971. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  38972. _super.call(this, name, alpha, beta, radius, target, scene);
  38973. this.interaxialDistance = interaxialDistance;
  38974. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38975. }
  38976. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  38977. return "AnaglyphArcRotateCamera";
  38978. };
  38979. return AnaglyphArcRotateCamera;
  38980. })(BABYLON.ArcRotateCamera);
  38981. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  38982. var AnaglyphGamepadCamera = (function (_super) {
  38983. __extends(AnaglyphGamepadCamera, _super);
  38984. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  38985. _super.call(this, name, position, scene);
  38986. this.interaxialDistance = interaxialDistance;
  38987. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38988. }
  38989. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  38990. return "AnaglyphGamepadCamera";
  38991. };
  38992. return AnaglyphGamepadCamera;
  38993. })(BABYLON.GamepadCamera);
  38994. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  38995. var AnaglyphUniversalCamera = (function (_super) {
  38996. __extends(AnaglyphUniversalCamera, _super);
  38997. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  38998. _super.call(this, name, position, scene);
  38999. this.interaxialDistance = interaxialDistance;
  39000. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39001. }
  39002. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  39003. return "AnaglyphUniversalCamera";
  39004. };
  39005. return AnaglyphUniversalCamera;
  39006. })(BABYLON.UniversalCamera);
  39007. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  39008. var StereoscopicFreeCamera = (function (_super) {
  39009. __extends(StereoscopicFreeCamera, _super);
  39010. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39011. _super.call(this, name, position, scene);
  39012. this.interaxialDistance = interaxialDistance;
  39013. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39014. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39015. }
  39016. StereoscopicFreeCamera.prototype.getTypeName = function () {
  39017. return "StereoscopicFreeCamera";
  39018. };
  39019. return StereoscopicFreeCamera;
  39020. })(BABYLON.FreeCamera);
  39021. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  39022. var StereoscopicArcRotateCamera = (function (_super) {
  39023. __extends(StereoscopicArcRotateCamera, _super);
  39024. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  39025. _super.call(this, name, alpha, beta, radius, target, scene);
  39026. this.interaxialDistance = interaxialDistance;
  39027. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39028. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39029. }
  39030. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  39031. return "StereoscopicArcRotateCamera";
  39032. };
  39033. return StereoscopicArcRotateCamera;
  39034. })(BABYLON.ArcRotateCamera);
  39035. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  39036. var StereoscopicGamepadCamera = (function (_super) {
  39037. __extends(StereoscopicGamepadCamera, _super);
  39038. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39039. _super.call(this, name, position, scene);
  39040. this.interaxialDistance = interaxialDistance;
  39041. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39042. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39043. }
  39044. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  39045. return "StereoscopicGamepadCamera";
  39046. };
  39047. return StereoscopicGamepadCamera;
  39048. })(BABYLON.GamepadCamera);
  39049. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  39050. var StereoscopicUniversalCamera = (function (_super) {
  39051. __extends(StereoscopicUniversalCamera, _super);
  39052. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39053. _super.call(this, name, position, scene);
  39054. this.interaxialDistance = interaxialDistance;
  39055. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39056. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39057. }
  39058. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  39059. return "StereoscopicUniversalCamera";
  39060. };
  39061. return StereoscopicUniversalCamera;
  39062. })(BABYLON.UniversalCamera);
  39063. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  39064. })(BABYLON || (BABYLON = {}));
  39065. //_______________________________________________________________
  39066. // Extracted from CubeMapGen:
  39067. // https://code.google.com/archive/p/cubemapgen/
  39068. //
  39069. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  39070. //_______________________________________________________________
  39071. var BABYLON;
  39072. (function (BABYLON) {
  39073. var Internals;
  39074. (function (Internals) {
  39075. var CMGBoundinBox = (function () {
  39076. function CMGBoundinBox() {
  39077. this.min = new BABYLON.Vector3(0, 0, 0);
  39078. this.max = new BABYLON.Vector3(0, 0, 0);
  39079. this.clear();
  39080. }
  39081. CMGBoundinBox.prototype.clear = function () {
  39082. this.min.x = CMGBoundinBox.MAX;
  39083. this.min.y = CMGBoundinBox.MAX;
  39084. this.min.z = CMGBoundinBox.MAX;
  39085. this.max.x = CMGBoundinBox.MIN;
  39086. this.max.y = CMGBoundinBox.MIN;
  39087. this.max.z = CMGBoundinBox.MIN;
  39088. };
  39089. CMGBoundinBox.prototype.augment = function (x, y, z) {
  39090. this.min.x = Math.min(this.min.x, x);
  39091. this.min.y = Math.min(this.min.y, y);
  39092. this.min.z = Math.min(this.min.z, z);
  39093. this.max.x = Math.max(this.max.x, x);
  39094. this.max.y = Math.max(this.max.y, y);
  39095. this.max.z = Math.max(this.max.z, z);
  39096. };
  39097. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  39098. this.min.x = Math.max(this.min.x, x);
  39099. this.min.y = Math.max(this.min.y, y);
  39100. this.min.z = Math.max(this.min.z, z);
  39101. };
  39102. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  39103. this.max.x = Math.min(this.max.x, x);
  39104. this.max.y = Math.min(this.max.y, y);
  39105. this.max.z = Math.min(this.max.z, z);
  39106. };
  39107. CMGBoundinBox.prototype.empty = function () {
  39108. if ((this.min.x > this.max.y) ||
  39109. (this.min.y > this.max.y) ||
  39110. (this.min.z > this.max.y)) {
  39111. return true;
  39112. }
  39113. else {
  39114. return false;
  39115. }
  39116. };
  39117. CMGBoundinBox.MAX = Number.MAX_VALUE;
  39118. CMGBoundinBox.MIN = Number.MIN_VALUE;
  39119. return CMGBoundinBox;
  39120. })();
  39121. var PMREMGenerator = (function () {
  39122. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  39123. this.input = input;
  39124. this.inputSize = inputSize;
  39125. this.outputSize = outputSize;
  39126. this.maxNumMipLevels = maxNumMipLevels;
  39127. this.numChannels = numChannels;
  39128. this.isFloat = isFloat;
  39129. this.specularPower = specularPower;
  39130. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  39131. this.excludeBase = excludeBase;
  39132. this.fixup = fixup;
  39133. this._outputSurface = [];
  39134. this._numMipLevels = 0;
  39135. }
  39136. PMREMGenerator.prototype.filterCubeMap = function () {
  39137. // Init cubemap processor
  39138. this.init();
  39139. // Filters the cubemap
  39140. this.filterCubeMapMipChain();
  39141. // Returns the filtered mips.
  39142. return this._outputSurface;
  39143. };
  39144. PMREMGenerator.prototype.init = function () {
  39145. var i;
  39146. var j;
  39147. var mipLevelSize;
  39148. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  39149. if (this.maxNumMipLevels == 0) {
  39150. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  39151. }
  39152. //first miplevel size
  39153. mipLevelSize = this.outputSize;
  39154. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  39155. for (j = 0; j < this.maxNumMipLevels; j++) {
  39156. this._outputSurface.length++;
  39157. this._outputSurface[j] = [];
  39158. //Iterate over faces for output images
  39159. for (i = 0; i < 6; i++) {
  39160. this._outputSurface[j].length++;
  39161. // Initializes a new array for the output.
  39162. if (this.isFloat) {
  39163. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  39164. }
  39165. else {
  39166. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  39167. }
  39168. }
  39169. //next mip level is half size
  39170. mipLevelSize >>= 1;
  39171. this._numMipLevels++;
  39172. //terminate if mip chain becomes too small
  39173. if (mipLevelSize == 0) {
  39174. this.maxNumMipLevels = j;
  39175. return;
  39176. }
  39177. }
  39178. };
  39179. //--------------------------------------------------------------------------------------
  39180. //Cube map filtering and mip chain generation.
  39181. // the cube map filtereing is specified using a number of parameters:
  39182. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  39183. // indicates the region of the hemisphere to filter over for each tap.
  39184. //
  39185. // Note that the top mip level is also a filtered version of the original input images
  39186. // as well in order to create mip chains for diffuse environment illumination.
  39187. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  39188. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  39189. //
  39190. // Then the mip angle used to genreate the next level of the mip chain from the first level
  39191. // is a_InitialMipAngle
  39192. //
  39193. // The angle for the subsequent levels of the mip chain are specified by their parents
  39194. // filtering angle and a per-level scale and bias
  39195. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  39196. //
  39197. //--------------------------------------------------------------------------------------
  39198. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  39199. // First, take count of the lighting model to modify SpecularPower
  39200. // 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;
  39201. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  39202. //Cone angle start (for generating subsequent mip levels)
  39203. var currentSpecularPower = this.specularPower;
  39204. //Build filter lookup tables based on the source miplevel size
  39205. this.precomputeFilterLookupTables(this.inputSize);
  39206. // Note that we need to filter the first level before generating mipmap
  39207. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  39208. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  39209. // TODO : Write a function to copy and scale the base mipmap in output
  39210. // I am just lazy here and just put a high specular power value, and do some if.
  39211. if (this.excludeBase && (levelIndex == 0)) {
  39212. // 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).
  39213. currentSpecularPower = 100000.0;
  39214. }
  39215. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  39216. var srcCubeImage = this.input;
  39217. var dstCubeImage = this._outputSurface[levelIndex];
  39218. var dstSize = this.outputSize >> levelIndex;
  39219. // Compute required angle.
  39220. var angle = this.getBaseFilterAngle(currentSpecularPower);
  39221. // filter cube surfaces
  39222. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  39223. // fix seams
  39224. if (this.fixup) {
  39225. this.fixupCubeEdges(dstCubeImage, dstSize);
  39226. }
  39227. // Decrease the specular power to generate the mipmap chain
  39228. // TODO : Use another method for Exclude (see first comment at start of the function
  39229. if (this.excludeBase && (levelIndex == 0)) {
  39230. currentSpecularPower = this.specularPower;
  39231. }
  39232. currentSpecularPower *= this.cosinePowerDropPerMip;
  39233. }
  39234. };
  39235. //--------------------------------------------------------------------------------------
  39236. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  39237. // It allow to optimize the texel to access base on the specular power.
  39238. //--------------------------------------------------------------------------------------
  39239. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  39240. // We want to find the alpha such that:
  39241. // cos(alpha)^cosinePower = epsilon
  39242. // That's: acos(epsilon^(1/cosinePower))
  39243. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  39244. var angle = 180.0;
  39245. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  39246. angle *= 180.0 / Math.PI; // Convert to degree
  39247. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  39248. return angle;
  39249. };
  39250. //--------------------------------------------------------------------------------------
  39251. //Builds the following lookup tables prior to filtering:
  39252. // -normalizer cube map
  39253. // -tap weight lookup table
  39254. //
  39255. //--------------------------------------------------------------------------------------
  39256. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  39257. var srcTexelAngle;
  39258. var iCubeFace;
  39259. //clear pre-existing normalizer cube map
  39260. this._normCubeMap = [];
  39261. //Normalized vectors per cubeface and per-texel solid angle
  39262. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  39263. };
  39264. //--------------------------------------------------------------------------------------
  39265. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  39266. //
  39267. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  39268. //
  39269. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  39270. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  39271. // below
  39272. //--------------------------------------------------------------------------------------
  39273. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  39274. var iCubeFace;
  39275. var u;
  39276. var v;
  39277. //iterate over cube faces
  39278. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39279. //First three channels for norm cube, and last channel for solid angle
  39280. this._normCubeMap.push(new Float32Array(size * size * 4));
  39281. //fast texture walk, build normalizer cube map
  39282. var facesData = this.input[iCubeFace];
  39283. for (v = 0; v < size; v++) {
  39284. for (u = 0; u < size; u++) {
  39285. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  39286. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  39287. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  39288. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  39289. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  39290. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  39291. }
  39292. }
  39293. }
  39294. };
  39295. //--------------------------------------------------------------------------------------
  39296. // Convert cubemap face texel coordinates and face idx to 3D vector
  39297. // note the U and V coords are integer coords and range from 0 to size-1
  39298. // this routine can be used to generate a normalizer cube map
  39299. //--------------------------------------------------------------------------------------
  39300. // SL BEGIN
  39301. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  39302. var nvcU;
  39303. var nvcV;
  39304. var tempVec;
  39305. // Change from original AMD code
  39306. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  39307. // + 0.5f is for texel center addressing
  39308. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  39309. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  39310. // warp fixup
  39311. if (fixup && size > 1) {
  39312. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  39313. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  39314. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  39315. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  39316. }
  39317. // Get current vector
  39318. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  39319. // U contribution
  39320. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  39321. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  39322. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  39323. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  39324. // V contribution and Sum
  39325. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  39326. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  39327. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  39328. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  39329. //add face axis
  39330. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  39331. PMREMGenerator._vectorTemp.x += faceAxis[0];
  39332. PMREMGenerator._vectorTemp.y += faceAxis[1];
  39333. PMREMGenerator._vectorTemp.z += faceAxis[2];
  39334. //normalize vector
  39335. PMREMGenerator._vectorTemp.normalize();
  39336. return PMREMGenerator._vectorTemp;
  39337. };
  39338. //--------------------------------------------------------------------------------------
  39339. // Convert 3D vector to cubemap face texel coordinates and face idx
  39340. // note the U and V coords are integer coords and range from 0 to size-1
  39341. // this routine can be used to generate a normalizer cube map
  39342. //
  39343. // returns face IDX and texel coords
  39344. //--------------------------------------------------------------------------------------
  39345. // SL BEGIN
  39346. /*
  39347. Mapping Texture Coordinates to Cube Map Faces
  39348. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  39349. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  39350. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  39351. map arrangement in Pixar's RenderMan package.
  39352. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  39353. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  39354. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  39355. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  39356. the major axis direction). The target column in the table below explains how the major axis direction
  39357. maps to the 2D image of a particular cube map target.
  39358. major axis
  39359. direction target sc tc ma
  39360. ---------- --------------------------------- --- --- ---
  39361. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  39362. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  39363. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  39364. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  39365. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  39366. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  39367. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  39368. an updated (s,t) is calculated as follows
  39369. s = ( sc/|ma| + 1 ) / 2
  39370. t = ( tc/|ma| + 1 ) / 2
  39371. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  39372. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  39373. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  39374. */
  39375. // Note this method return U and V in range from 0 to size-1
  39376. // SL END
  39377. // Store the information in vector3 for convenience (faceindex, u, v)
  39378. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  39379. var maxCoord;
  39380. var faceIdx;
  39381. //absolute value 3
  39382. var absX = Math.abs(x);
  39383. var absY = Math.abs(y);
  39384. var absZ = Math.abs(z);
  39385. if (absX >= absY && absX >= absZ) {
  39386. maxCoord = absX;
  39387. if (x >= 0) {
  39388. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  39389. }
  39390. else {
  39391. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  39392. }
  39393. }
  39394. else if (absY >= absX && absY >= absZ) {
  39395. maxCoord = absY;
  39396. if (y >= 0) {
  39397. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  39398. }
  39399. else {
  39400. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  39401. }
  39402. }
  39403. else {
  39404. maxCoord = absZ;
  39405. if (z >= 0) {
  39406. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  39407. }
  39408. else {
  39409. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  39410. }
  39411. }
  39412. //divide through by max coord so face vector lies on cube face
  39413. var scale = 1 / maxCoord;
  39414. x *= scale;
  39415. y *= scale;
  39416. z *= scale;
  39417. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  39418. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  39419. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  39420. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  39421. // Modify original AMD code to return value from 0 to Size - 1
  39422. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  39423. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  39424. PMREMGenerator._vectorTemp.x = faceIdx;
  39425. PMREMGenerator._vectorTemp.y = u;
  39426. PMREMGenerator._vectorTemp.z = v;
  39427. return PMREMGenerator._vectorTemp;
  39428. };
  39429. //--------------------------------------------------------------------------------------
  39430. //Original code from Ignacio CastaÒo
  39431. // This formula is from Manne ÷hrstrˆm's thesis.
  39432. // Take two coordiantes in the range [-1, 1] that define a portion of a
  39433. // cube face and return the area of the projection of that portion on the
  39434. // surface of the sphere.
  39435. //--------------------------------------------------------------------------------------
  39436. PMREMGenerator.prototype.areaElement = function (x, y) {
  39437. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  39438. };
  39439. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  39440. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  39441. // (+ 0.5f is for texel center addressing)
  39442. u = (2.0 * (u + 0.5) / size) - 1.0;
  39443. v = (2.0 * (v + 0.5) / size) - 1.0;
  39444. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  39445. var invResolution = 1.0 / size;
  39446. // U and V are the -1..1 texture coordinate on the current face.
  39447. // Get projected area for this texel
  39448. var x0 = u - invResolution;
  39449. var y0 = v - invResolution;
  39450. var x1 = u + invResolution;
  39451. var y1 = v + invResolution;
  39452. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  39453. return solidAngle;
  39454. };
  39455. //--------------------------------------------------------------------------------------
  39456. //The key to the speed of these filtering routines is to quickly define a per-face
  39457. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  39458. // Later these pixels are selectively processed based on their dot products to see if
  39459. // they reside within the filtering cone.
  39460. //
  39461. //This is done by computing the smallest per-texel angle to get a conservative estimate
  39462. // of the number of texels needed to be covered in width and height order to filter the
  39463. // region. the bounding box for the center taps face is defined first, and if the
  39464. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  39465. // defined next
  39466. //--------------------------------------------------------------------------------------
  39467. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  39468. // note that pixels within these regions may be rejected
  39469. // based on the anlge
  39470. var iCubeFace;
  39471. var u;
  39472. var v;
  39473. // bounding box per face to specify region to process
  39474. var filterExtents = [];
  39475. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39476. filterExtents.push(new CMGBoundinBox());
  39477. }
  39478. // min angle a src texel can cover (in degrees)
  39479. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  39480. // angle about center tap to define filter cone
  39481. // filter angle is 1/2 the cone angle
  39482. var filterAngle = filterConeAngle / 2.0;
  39483. //ensure filter angle is larger than a texel
  39484. if (filterAngle < srcTexelAngle) {
  39485. filterAngle = srcTexelAngle;
  39486. }
  39487. //ensure filter cone is always smaller than the hemisphere
  39488. if (filterAngle > 90.0) {
  39489. filterAngle = 90.0;
  39490. }
  39491. // the maximum number of texels in 1D the filter cone angle will cover
  39492. // used to determine bounding box size for filter extents
  39493. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  39494. // ensure conservative region always covers at least one texel
  39495. if (filterSize < 1) {
  39496. filterSize = 1;
  39497. }
  39498. // dotProdThresh threshold based on cone angle to determine whether or not taps
  39499. // reside within the cone angle
  39500. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  39501. // process required faces
  39502. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39503. //iterate over dst cube map face texel
  39504. for (v = 0; v < dstSize; v++) {
  39505. for (u = 0; u < dstSize; u++) {
  39506. //get center tap direction
  39507. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  39508. //clear old per-face filter extents
  39509. this.clearFilterExtents(filterExtents);
  39510. //define per-face filter extents
  39511. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  39512. //perform filtering of src faces using filter extents
  39513. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  39514. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  39515. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  39516. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  39517. }
  39518. }
  39519. }
  39520. };
  39521. //--------------------------------------------------------------------------------------
  39522. //Clear filter extents for the 6 cube map faces
  39523. //--------------------------------------------------------------------------------------
  39524. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  39525. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  39526. filterExtents[iCubeFaces].clear();
  39527. }
  39528. };
  39529. //--------------------------------------------------------------------------------------
  39530. //Define per-face bounding box filter extents
  39531. //
  39532. // These define conservative texel regions in each of the faces the filter can possibly
  39533. // process. When the pixels in the regions are actually processed, the dot product
  39534. // between the tap vector and the center tap vector is used to determine the weight of
  39535. // the tap and whether or not the tap is within the cone.
  39536. //
  39537. //--------------------------------------------------------------------------------------
  39538. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  39539. //neighboring face and bleed over amount, and width of BBOX for
  39540. // left, right, top, and bottom edges of this face
  39541. var bleedOverAmount = [0, 0, 0, 0];
  39542. var bleedOverBBoxMin = [0, 0, 0, 0];
  39543. var bleedOverBBoxMax = [0, 0, 0, 0];
  39544. var neighborFace;
  39545. var neighborEdge;
  39546. var oppositeFaceIdx;
  39547. //get face idx, and u, v info from center tap dir
  39548. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  39549. var faceIdx = result.x;
  39550. var u = result.y;
  39551. var v = result.z;
  39552. //define bbox size within face
  39553. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  39554. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  39555. filterExtents[faceIdx].clampMin(0, 0, 0);
  39556. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  39557. //u and v extent in face corresponding to center tap
  39558. var minU = filterExtents[faceIdx].min.x;
  39559. var minV = filterExtents[faceIdx].min.y;
  39560. var maxU = filterExtents[faceIdx].max.x;
  39561. var maxV = filterExtents[faceIdx].max.y;
  39562. //bleed over amounts for face across u=0 edge (left)
  39563. bleedOverAmount[0] = (bboxSize - u);
  39564. bleedOverBBoxMin[0] = minV;
  39565. bleedOverBBoxMax[0] = maxV;
  39566. //bleed over amounts for face across u=1 edge (right)
  39567. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  39568. bleedOverBBoxMin[1] = minV;
  39569. bleedOverBBoxMax[1] = maxV;
  39570. //bleed over to face across v=0 edge (up)
  39571. bleedOverAmount[2] = (bboxSize - v);
  39572. bleedOverBBoxMin[2] = minU;
  39573. bleedOverBBoxMax[2] = maxU;
  39574. //bleed over to face across v=1 edge (down)
  39575. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  39576. bleedOverBBoxMin[3] = minU;
  39577. bleedOverBBoxMax[3] = maxU;
  39578. //compute bleed over regions in neighboring faces
  39579. for (var i = 0; i < 4; i++) {
  39580. if (bleedOverAmount[i] > 0) {
  39581. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  39582. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  39583. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  39584. // be flipped: the cases are
  39585. // if a left edge mates with a left or bottom edge on the neighbor
  39586. // if a top edge mates with a top or right edge on the neighbor
  39587. // if a right edge mates with a right or top edge on the neighbor
  39588. // if a bottom edge mates with a bottom or left edge on the neighbor
  39589. //Seeing as the edges are enumerated as follows
  39590. // left =0
  39591. // right =1
  39592. // top =2
  39593. // bottom =3
  39594. //
  39595. // so if the edge enums are the same, or the sum of the enums == 3,
  39596. // the bbox needs to be flipped
  39597. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  39598. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  39599. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  39600. }
  39601. //The way the bounding box is extended onto the neighboring face
  39602. // depends on which edge of neighboring face abuts with this one
  39603. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  39604. case PMREMGenerator.CP_EDGE_LEFT:
  39605. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  39606. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  39607. break;
  39608. case PMREMGenerator.CP_EDGE_RIGHT:
  39609. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  39610. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  39611. break;
  39612. case PMREMGenerator.CP_EDGE_TOP:
  39613. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  39614. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  39615. break;
  39616. case PMREMGenerator.CP_EDGE_BOTTOM:
  39617. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  39618. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  39619. break;
  39620. }
  39621. //clamp filter extents in non-center tap faces to remain within surface
  39622. filterExtents[neighborFace].clampMin(0, 0, 0);
  39623. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  39624. }
  39625. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  39626. // from the center tap face, then process the opposite face entirely for now.
  39627. //Note that the cases in which this happens, what usually happens is that
  39628. // more than one edge bleeds onto the opposite face, and the bounding box
  39629. // encompasses the entire cube map face.
  39630. if (bleedOverAmount[i] > srcSize) {
  39631. //determine opposite face
  39632. switch (faceIdx) {
  39633. case PMREMGenerator.CP_FACE_X_POS:
  39634. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  39635. break;
  39636. case PMREMGenerator.CP_FACE_X_NEG:
  39637. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  39638. break;
  39639. case PMREMGenerator.CP_FACE_Y_POS:
  39640. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  39641. break;
  39642. case PMREMGenerator.CP_FACE_Y_NEG:
  39643. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  39644. break;
  39645. case PMREMGenerator.CP_FACE_Z_POS:
  39646. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  39647. break;
  39648. case PMREMGenerator.CP_FACE_Z_NEG:
  39649. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  39650. break;
  39651. default:
  39652. break;
  39653. }
  39654. //just encompass entire face for now
  39655. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  39656. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  39657. }
  39658. }
  39659. };
  39660. //--------------------------------------------------------------------------------------
  39661. //ProcessFilterExtents
  39662. // Process bounding box in each cube face
  39663. //
  39664. //--------------------------------------------------------------------------------------
  39665. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  39666. //accumulators are 64-bit floats in order to have the precision needed
  39667. // over a summation of a large number of pixels
  39668. var dstAccum = [0, 0, 0, 0];
  39669. var weightAccum = 0;
  39670. var k = 0;
  39671. var nSrcChannels = this.numChannels;
  39672. // norm cube map and srcCubeMap have same face width
  39673. var faceWidth = srcSize;
  39674. //amount to add to pointer to move to next scanline in images
  39675. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  39676. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  39677. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  39678. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  39679. // iterate over cubefaces
  39680. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  39681. //if bbox is non empty
  39682. if (!filterExtents[iFaceIdx].empty()) {
  39683. var uStart = filterExtents[iFaceIdx].min.x;
  39684. var vStart = filterExtents[iFaceIdx].min.y;
  39685. var uEnd = filterExtents[iFaceIdx].max.x;
  39686. var vEnd = filterExtents[iFaceIdx].max.y;
  39687. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  39688. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  39689. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  39690. for (var v = vStart; v <= vEnd; v++) {
  39691. var normCubeRowWalk = 0;
  39692. var srcCubeRowWalk = 0;
  39693. for (var u = uStart; u <= uEnd; u++) {
  39694. //pointer to direction in cube map associated with texel
  39695. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  39696. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  39697. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  39698. //check dot product to see if texel is within cone
  39699. var tapDotProd = texelVectX * centerTapDir.x +
  39700. texelVectY * centerTapDir.y +
  39701. texelVectZ * centerTapDir.z;
  39702. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  39703. //solid angle stored in 4th channel of normalizer/solid angle cube map
  39704. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  39705. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  39706. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  39707. // so just adding one to specularpower do the trick.
  39708. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  39709. //iterate over channels
  39710. for (k = 0; k < nSrcChannels; k++) {
  39711. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  39712. srcCubeRowWalk++;
  39713. }
  39714. weightAccum += weight; //accumulate weight
  39715. }
  39716. else {
  39717. //step across source pixel
  39718. srcCubeRowWalk += nSrcChannels;
  39719. }
  39720. normCubeRowWalk += 4; // 4 channels per norm cube map.
  39721. }
  39722. startIndexNormCubeMap += normCubePitch;
  39723. startIndexSrcCubeMap += srcCubePitch;
  39724. }
  39725. }
  39726. }
  39727. //divide through by weights if weight is non zero
  39728. if (weightAccum != 0.0) {
  39729. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  39730. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  39731. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  39732. if (this.numChannels > 3) {
  39733. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  39734. }
  39735. }
  39736. else {
  39737. // otherwise sample nearest
  39738. // get face idx and u, v texel coordinate in face
  39739. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  39740. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  39741. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  39742. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  39743. if (this.numChannels > 3) {
  39744. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  39745. }
  39746. }
  39747. return PMREMGenerator._vectorTemp;
  39748. };
  39749. //--------------------------------------------------------------------------------------
  39750. // Fixup cube edges
  39751. //
  39752. // average texels on cube map faces across the edges
  39753. // WARP/BENT Method Only.
  39754. //--------------------------------------------------------------------------------------
  39755. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  39756. var k;
  39757. var j;
  39758. var i;
  39759. var iFace;
  39760. var iCorner = 0;
  39761. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  39762. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  39763. // note that if functionality to filter across the three texels for each corner, then
  39764. //indexed by corner and face idx. the array contains the face the start points belongs to.
  39765. var cornerPtr = [
  39766. [[], [], []],
  39767. [[], [], []],
  39768. [[], [], []],
  39769. [[], [], []],
  39770. [[], [], []],
  39771. [[], [], []],
  39772. [[], [], []],
  39773. [[], [], []]
  39774. ];
  39775. //if there is no fixup, or fixup width = 0, do nothing
  39776. if (cubeMapSize < 1) {
  39777. return;
  39778. }
  39779. //special case 1x1 cubemap, average face colors
  39780. if (cubeMapSize == 1) {
  39781. //iterate over channels
  39782. for (k = 0; k < this.numChannels; k++) {
  39783. var accum = 0.0;
  39784. //iterate over faces to accumulate face colors
  39785. for (iFace = 0; iFace < 6; iFace++) {
  39786. accum += cubeMap[iFace][k];
  39787. }
  39788. //compute average over 6 face colors
  39789. accum /= 6.0;
  39790. //iterate over faces to distribute face colors
  39791. for (iFace = 0; iFace < 6; iFace++) {
  39792. cubeMap[iFace][k] = accum;
  39793. }
  39794. }
  39795. return;
  39796. }
  39797. //iterate over faces to collect list of corner texel pointers
  39798. for (iFace = 0; iFace < 6; iFace++) {
  39799. //the 4 corner pointers for this face
  39800. faceCornerStartIndicies[0] = [iFace, 0];
  39801. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  39802. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  39803. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  39804. //iterate over face corners to collect cube corner pointers
  39805. for (iCorner = 0; iCorner < 4; iCorner++) {
  39806. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  39807. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  39808. cornerNumPtrs[corner]++;
  39809. }
  39810. }
  39811. //iterate over corners to average across corner tap values
  39812. for (iCorner = 0; iCorner < 8; iCorner++) {
  39813. for (k = 0; k < this.numChannels; k++) {
  39814. var cornerTapAccum = 0.0;
  39815. //iterate over corner texels and average results
  39816. for (i = 0; i < 3; i++) {
  39817. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  39818. }
  39819. //divide by 3 to compute average of corner tap values
  39820. cornerTapAccum *= (1.0 / 3.0);
  39821. //iterate over corner texels and average results
  39822. for (i = 0; i < 3; i++) {
  39823. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  39824. }
  39825. }
  39826. }
  39827. //iterate over the twelve edges of the cube to average across edges
  39828. for (i = 0; i < 12; i++) {
  39829. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  39830. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  39831. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  39832. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  39833. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  39834. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  39835. var edgeWalk = 0;
  39836. var neighborEdgeWalk = 0;
  39837. //Determine walking pointers based on edge type
  39838. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  39839. switch (edge) {
  39840. case PMREMGenerator.CP_EDGE_LEFT:
  39841. // no change to faceEdgeStartPtr
  39842. edgeWalk = this.numChannels * cubeMapSize;
  39843. break;
  39844. case PMREMGenerator.CP_EDGE_RIGHT:
  39845. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  39846. edgeWalk = this.numChannels * cubeMapSize;
  39847. break;
  39848. case PMREMGenerator.CP_EDGE_TOP:
  39849. // no change to faceEdgeStartPtr
  39850. edgeWalk = this.numChannels;
  39851. break;
  39852. case PMREMGenerator.CP_EDGE_BOTTOM:
  39853. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  39854. edgeWalk = this.numChannels;
  39855. break;
  39856. }
  39857. //For certain types of edge abutments, the neighbor edge walk needs to
  39858. // be flipped: the cases are
  39859. // if a left edge mates with a left or bottom edge on the neighbor
  39860. // if a top edge mates with a top or right edge on the neighbor
  39861. // if a right edge mates with a right or top edge on the neighbor
  39862. // if a bottom edge mates with a bottom or left edge on the neighbor
  39863. //Seeing as the edges are enumerated as follows
  39864. // left =0
  39865. // right =1
  39866. // top =2
  39867. // bottom =3
  39868. //
  39869. //If the edge enums are the same, or the sum of the enums == 3,
  39870. // the neighbor edge walk needs to be flipped
  39871. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  39872. switch (neighborEdge) {
  39873. case PMREMGenerator.CP_EDGE_LEFT:
  39874. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  39875. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  39876. break;
  39877. case PMREMGenerator.CP_EDGE_RIGHT:
  39878. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  39879. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  39880. break;
  39881. case PMREMGenerator.CP_EDGE_TOP:
  39882. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  39883. neighborEdgeWalk = -this.numChannels;
  39884. break;
  39885. case PMREMGenerator.CP_EDGE_BOTTOM:
  39886. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  39887. neighborEdgeWalk = -this.numChannels;
  39888. break;
  39889. }
  39890. }
  39891. else {
  39892. //swapped direction neighbor edge walk
  39893. switch (neighborEdge) {
  39894. case PMREMGenerator.CP_EDGE_LEFT:
  39895. //no change to neighborEdgeStartPtr for this case since it points
  39896. // to the upper left corner already
  39897. neighborEdgeWalk = this.numChannels * cubeMapSize;
  39898. break;
  39899. case PMREMGenerator.CP_EDGE_RIGHT:
  39900. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  39901. neighborEdgeWalk = this.numChannels * cubeMapSize;
  39902. break;
  39903. case PMREMGenerator.CP_EDGE_TOP:
  39904. //no change to neighborEdgeStartPtr for this case since it points
  39905. // to the upper left corner already
  39906. neighborEdgeWalk = this.numChannels;
  39907. break;
  39908. case PMREMGenerator.CP_EDGE_BOTTOM:
  39909. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  39910. neighborEdgeWalk = this.numChannels;
  39911. break;
  39912. }
  39913. }
  39914. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  39915. //nearby neighborhood
  39916. //step ahead one texel on edge
  39917. edgeStartIndex += edgeWalk;
  39918. neighborEdgeStartIndex += neighborEdgeWalk;
  39919. // note that this loop does not process the corner texels, since they have already been
  39920. // averaged across faces across earlier
  39921. for (j = 1; j < (cubeMapSize - 1); j++) {
  39922. //for each set of taps along edge, average them
  39923. // and rewrite the results into the edges
  39924. for (k = 0; k < this.numChannels; k++) {
  39925. var edgeTap = cubeMap[face][edgeStartIndex + k];
  39926. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  39927. //compute average of tap intensity values
  39928. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  39929. //propagate average of taps to edge taps
  39930. cubeMap[face][edgeStartIndex + k] = avgTap;
  39931. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  39932. }
  39933. edgeStartIndex += edgeWalk;
  39934. neighborEdgeStartIndex += neighborEdgeWalk;
  39935. }
  39936. }
  39937. };
  39938. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  39939. PMREMGenerator.CP_UDIR = 0;
  39940. PMREMGenerator.CP_VDIR = 1;
  39941. PMREMGenerator.CP_FACEAXIS = 2;
  39942. //used to index cube faces
  39943. PMREMGenerator.CP_FACE_X_POS = 0;
  39944. PMREMGenerator.CP_FACE_X_NEG = 1;
  39945. PMREMGenerator.CP_FACE_Y_POS = 2;
  39946. PMREMGenerator.CP_FACE_Y_NEG = 3;
  39947. PMREMGenerator.CP_FACE_Z_POS = 4;
  39948. PMREMGenerator.CP_FACE_Z_NEG = 5;
  39949. //used to index image edges
  39950. // NOTE.. the actual number corresponding to the edge is important
  39951. // do not change these, or the code will break
  39952. //
  39953. // CP_EDGE_LEFT is u = 0
  39954. // CP_EDGE_RIGHT is u = width-1
  39955. // CP_EDGE_TOP is v = 0
  39956. // CP_EDGE_BOTTOM is v = height-1
  39957. PMREMGenerator.CP_EDGE_LEFT = 0;
  39958. PMREMGenerator.CP_EDGE_RIGHT = 1;
  39959. PMREMGenerator.CP_EDGE_TOP = 2;
  39960. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  39961. //corners of CUBE map (P or N specifys if it corresponds to the
  39962. // positive or negative direction each of X, Y, and Z
  39963. PMREMGenerator.CP_CORNER_NNN = 0;
  39964. PMREMGenerator.CP_CORNER_NNP = 1;
  39965. PMREMGenerator.CP_CORNER_NPN = 2;
  39966. PMREMGenerator.CP_CORNER_NPP = 3;
  39967. PMREMGenerator.CP_CORNER_PNN = 4;
  39968. PMREMGenerator.CP_CORNER_PNP = 5;
  39969. PMREMGenerator.CP_CORNER_PPN = 6;
  39970. PMREMGenerator.CP_CORNER_PPP = 7;
  39971. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  39972. //3x2 matrices that map cube map indexing vectors in 3d
  39973. // (after face selection and divide through by the
  39974. // _ABSOLUTE VALUE_ of the max coord)
  39975. // into NVC space
  39976. //Note this currently assumes the D3D cube face ordering and orientation
  39977. PMREMGenerator._sgFace2DMapping = [
  39978. //XPOS face
  39979. [[0, 0, -1],
  39980. [0, -1, 0],
  39981. [1, 0, 0]],
  39982. //XNEG face
  39983. [[0, 0, 1],
  39984. [0, -1, 0],
  39985. [-1, 0, 0]],
  39986. //YPOS face
  39987. [[1, 0, 0],
  39988. [0, 0, 1],
  39989. [0, 1, 0]],
  39990. //YNEG face
  39991. [[1, 0, 0],
  39992. [0, 0, -1],
  39993. [0, -1, 0]],
  39994. //ZPOS face
  39995. [[1, 0, 0],
  39996. [0, -1, 0],
  39997. [0, 0, 1]],
  39998. //ZNEG face
  39999. [[-1, 0, 0],
  40000. [0, -1, 0],
  40001. [0, 0, -1]],
  40002. ];
  40003. //------------------------------------------------------------------------------
  40004. // D3D cube map face specification
  40005. // mapping from 3D x,y,z cube map lookup coordinates
  40006. // to 2D within face u,v coordinates
  40007. //
  40008. // --------------------> U direction
  40009. // | (within-face texture space)
  40010. // | _____
  40011. // | | |
  40012. // | | +Y |
  40013. // | _____|_____|_____ _____
  40014. // | | | | | |
  40015. // | | -X | +Z | +X | -Z |
  40016. // | |_____|_____|_____|_____|
  40017. // | | |
  40018. // | | -Y |
  40019. // | |_____|
  40020. // |
  40021. // v V direction
  40022. // (within-face texture space)
  40023. //------------------------------------------------------------------------------
  40024. //Information about neighbors and how texture coorrdinates change across faces
  40025. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  40026. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  40027. //Note this currently assumes the D3D cube face ordering and orientation
  40028. PMREMGenerator._sgCubeNgh = [
  40029. //XPOS face
  40030. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40031. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40032. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40033. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  40034. //XNEG face
  40035. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40036. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  40037. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  40038. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  40039. //YPOS face
  40040. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  40041. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  40042. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  40043. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  40044. //YNEG face
  40045. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  40046. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40047. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40048. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  40049. //ZPOS face
  40050. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40051. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  40052. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40053. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  40054. //ZNEG face
  40055. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40056. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40057. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  40058. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  40059. ];
  40060. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  40061. // this table is used to average over the edges.
  40062. PMREMGenerator._sgCubeEdgeList = [
  40063. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  40064. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40065. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  40066. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40067. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40068. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40069. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  40070. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  40071. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  40072. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40073. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  40074. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  40075. ];
  40076. //Information about which of the 8 cube corners are correspond to the
  40077. // the 4 corners in each cube face
  40078. // the order is upper left, upper right, lower left, lower right
  40079. PMREMGenerator._sgCubeCornerList = [
  40080. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  40081. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  40082. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  40083. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  40084. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  40085. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  40086. ];
  40087. return PMREMGenerator;
  40088. })();
  40089. Internals.PMREMGenerator = PMREMGenerator;
  40090. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40091. })(BABYLON || (BABYLON = {}));
  40092. var BABYLON;
  40093. (function (BABYLON) {
  40094. var Internals;
  40095. (function (Internals) {
  40096. var FileFaceOrientation = (function () {
  40097. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  40098. this.name = name;
  40099. this.worldAxisForNormal = worldAxisForNormal;
  40100. this.worldAxisForFileX = worldAxisForFileX;
  40101. this.worldAxisForFileY = worldAxisForFileY;
  40102. }
  40103. return FileFaceOrientation;
  40104. })();
  40105. ;
  40106. var CubeMapToSphericalPolynomialTools = (function () {
  40107. function CubeMapToSphericalPolynomialTools() {
  40108. }
  40109. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  40110. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  40111. var totalSolidAngle = 0.0;
  40112. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  40113. var du = 2.0 / cubeInfo.size;
  40114. var dv = du;
  40115. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  40116. var minUV = du * 0.5 - 1.0;
  40117. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  40118. var fileFace = this.FileFaces[faceIndex];
  40119. var dataArray = cubeInfo[fileFace.name];
  40120. var v = minUV;
  40121. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  40122. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  40123. // Because SP is still linear, so summation is fine in that basis.
  40124. for (var y = 0; y < cubeInfo.size; y++) {
  40125. var u = minUV;
  40126. for (var x = 0; x < cubeInfo.size; x++) {
  40127. // World direction (not normalised)
  40128. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  40129. worldDirection.normalize();
  40130. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  40131. if (1) {
  40132. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  40133. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  40134. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  40135. var color = new BABYLON.Color3(r, g, b);
  40136. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40137. }
  40138. else {
  40139. if (faceIndex == 0) {
  40140. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40141. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40142. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40143. }
  40144. else if (faceIndex == 1) {
  40145. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40146. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40147. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40148. }
  40149. else if (faceIndex == 2) {
  40150. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40151. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40152. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40153. }
  40154. else if (faceIndex == 3) {
  40155. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40156. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40157. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40158. }
  40159. else if (faceIndex == 4) {
  40160. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40161. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40162. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40163. }
  40164. else if (faceIndex == 5) {
  40165. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40166. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40167. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40168. }
  40169. 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]);
  40170. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40171. }
  40172. totalSolidAngle += deltaSolidAngle;
  40173. u += du;
  40174. }
  40175. v += dv;
  40176. }
  40177. }
  40178. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  40179. var correction = correctSolidAngle / totalSolidAngle;
  40180. sphericalHarmonics.scale(correction);
  40181. // Additionally scale by pi -- audit needed
  40182. sphericalHarmonics.scale(1.0 / Math.PI);
  40183. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  40184. };
  40185. CubeMapToSphericalPolynomialTools.FileFaces = [
  40186. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  40187. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  40188. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  40189. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  40190. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  40191. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  40192. ];
  40193. return CubeMapToSphericalPolynomialTools;
  40194. })();
  40195. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  40196. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40197. })(BABYLON || (BABYLON = {}));
  40198. var BABYLON;
  40199. (function (BABYLON) {
  40200. var Internals;
  40201. (function (Internals) {
  40202. var PanoramaToCubeMapTools = (function () {
  40203. function PanoramaToCubeMapTools() {
  40204. }
  40205. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  40206. if (!float32Array) {
  40207. throw "ConvertPanoramaToCubemap: input cannot be null";
  40208. }
  40209. if (float32Array.length != inputWidth * inputHeight * 3) {
  40210. throw "ConvertPanoramaToCubemap: input size is wrong";
  40211. }
  40212. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  40213. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  40214. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  40215. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  40216. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  40217. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  40218. return {
  40219. front: textureFront,
  40220. back: textureBack,
  40221. left: textureLeft,
  40222. right: textureRight,
  40223. up: textureUp,
  40224. down: textureDown,
  40225. size: size
  40226. };
  40227. };
  40228. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  40229. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  40230. var textureArray = new Float32Array(buffer);
  40231. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  40232. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  40233. var dy = 1 / texSize;
  40234. var fy = 0;
  40235. for (var y = 0; y < texSize; y++) {
  40236. var xv1 = faceData[0];
  40237. var xv2 = faceData[2];
  40238. for (var x = 0; x < texSize; x++) {
  40239. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  40240. v.normalize();
  40241. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  40242. // 3 channels per pixels
  40243. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  40244. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  40245. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  40246. xv1 = xv1.add(rotDX1);
  40247. xv2 = xv2.add(rotDX2);
  40248. }
  40249. fy += dy;
  40250. }
  40251. return textureArray;
  40252. };
  40253. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  40254. var theta = Math.atan2(vDir.z, vDir.x);
  40255. var phi = Math.acos(vDir.y);
  40256. while (theta < -Math.PI)
  40257. theta += 2 * Math.PI;
  40258. while (theta > Math.PI)
  40259. theta -= 2 * Math.PI;
  40260. var dx = theta / Math.PI;
  40261. var dy = phi / Math.PI;
  40262. // recenter.
  40263. dx = dx * 0.5 + 0.5;
  40264. var px = Math.round(dx * inputWidth);
  40265. if (px < 0)
  40266. px = 0;
  40267. else if (px >= inputWidth)
  40268. px = inputWidth - 1;
  40269. var py = Math.round(dy * inputHeight);
  40270. if (py < 0)
  40271. py = 0;
  40272. else if (py >= inputHeight)
  40273. py = inputHeight - 1;
  40274. var inputY = (inputHeight - py - 1);
  40275. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  40276. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  40277. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  40278. return {
  40279. r: r,
  40280. g: g,
  40281. b: b
  40282. };
  40283. };
  40284. PanoramaToCubeMapTools.FACE_FRONT = [
  40285. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40286. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40287. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40288. new BABYLON.Vector3(1.0, 1.0, -1.0)
  40289. ];
  40290. PanoramaToCubeMapTools.FACE_BACK = [
  40291. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40292. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40293. new BABYLON.Vector3(1.0, 1.0, 1.0),
  40294. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  40295. ];
  40296. PanoramaToCubeMapTools.FACE_RIGHT = [
  40297. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40298. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40299. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40300. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40301. ];
  40302. PanoramaToCubeMapTools.FACE_LEFT = [
  40303. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40304. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40305. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40306. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  40307. ];
  40308. PanoramaToCubeMapTools.FACE_DOWN = [
  40309. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40310. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40311. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40312. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40313. ];
  40314. PanoramaToCubeMapTools.FACE_UP = [
  40315. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40316. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40317. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40318. new BABYLON.Vector3(1.0, -1.0, -1.0)
  40319. ];
  40320. return PanoramaToCubeMapTools;
  40321. })();
  40322. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  40323. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40324. })(BABYLON || (BABYLON = {}));
  40325. var BABYLON;
  40326. (function (BABYLON) {
  40327. var Internals;
  40328. (function (Internals) {
  40329. ;
  40330. var HDRTools = (function () {
  40331. function HDRTools() {
  40332. }
  40333. HDRTools.Ldexp = function (mantissa, exponent) {
  40334. if (exponent > 1023) {
  40335. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  40336. }
  40337. if (exponent < -1074) {
  40338. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  40339. }
  40340. return mantissa * Math.pow(2, exponent);
  40341. };
  40342. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  40343. if (exponent > 0) {
  40344. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  40345. float32array[index + 0] = red * exponent;
  40346. float32array[index + 1] = green * exponent;
  40347. float32array[index + 2] = blue * exponent;
  40348. }
  40349. else {
  40350. float32array[index + 0] = 0;
  40351. float32array[index + 1] = 0;
  40352. float32array[index + 2] = 0;
  40353. }
  40354. };
  40355. HDRTools.readStringLine = function (uint8array, startIndex) {
  40356. var line = "";
  40357. var character = "";
  40358. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  40359. character = String.fromCharCode(uint8array[i]);
  40360. if (character == "\n") {
  40361. break;
  40362. }
  40363. line += character;
  40364. }
  40365. return line;
  40366. };
  40367. /* minimal header reading. modify if you want to parse more information */
  40368. HDRTools.RGBE_ReadHeader = function (uint8array) {
  40369. var height = 0;
  40370. var width = 0;
  40371. var line = this.readStringLine(uint8array, 0);
  40372. if (line[0] != '#' || line[1] != '?') {
  40373. throw "Bad HDR Format.";
  40374. }
  40375. var endOfHeader = false;
  40376. var findFormat = false;
  40377. var lineIndex = 0;
  40378. do {
  40379. lineIndex += (line.length + 1);
  40380. line = this.readStringLine(uint8array, lineIndex);
  40381. if (line == "FORMAT=32-bit_rle_rgbe") {
  40382. findFormat = true;
  40383. }
  40384. else if (line.length == 0) {
  40385. endOfHeader = true;
  40386. }
  40387. } while (!endOfHeader);
  40388. if (!findFormat) {
  40389. throw "HDR Bad header format, unsupported FORMAT";
  40390. }
  40391. lineIndex += (line.length + 1);
  40392. line = this.readStringLine(uint8array, lineIndex);
  40393. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  40394. var match = sizeRegexp.exec(line);
  40395. // TODO. Support +Y and -X if needed.
  40396. if (match.length < 3) {
  40397. throw "HDR Bad header format, no size";
  40398. }
  40399. width = parseInt(match[2]);
  40400. height = parseInt(match[1]);
  40401. if (width < 8 || width > 0x7fff) {
  40402. throw "HDR Bad header format, unsupported size";
  40403. }
  40404. lineIndex += (line.length + 1);
  40405. return {
  40406. height: height,
  40407. width: width,
  40408. dataPosition: lineIndex
  40409. };
  40410. };
  40411. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  40412. var uint8array = new Uint8Array(buffer);
  40413. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  40414. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40415. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  40416. return cubeMapData;
  40417. };
  40418. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  40419. // Keep for multi format supports.
  40420. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40421. };
  40422. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  40423. var num_scanlines = hdrInfo.height;
  40424. var scanline_width = hdrInfo.width;
  40425. var a, b, c, d, count;
  40426. var dataIndex = hdrInfo.dataPosition;
  40427. var index = 0, endIndex = 0, i = 0;
  40428. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  40429. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  40430. // 3 channels of 4 bytes per pixel in float.
  40431. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  40432. var resultArray = new Float32Array(resultBuffer);
  40433. // read in each successive scanline
  40434. while (num_scanlines > 0) {
  40435. a = uint8array[dataIndex++];
  40436. b = uint8array[dataIndex++];
  40437. c = uint8array[dataIndex++];
  40438. d = uint8array[dataIndex++];
  40439. if (a != 2 || b != 2 || (c & 0x80)) {
  40440. // this file is not run length encoded
  40441. throw "HDR Bad header format, not RLE";
  40442. }
  40443. if (((c << 8) | d) != scanline_width) {
  40444. throw "HDR Bad header format, wrong scan line width";
  40445. }
  40446. index = 0;
  40447. // read each of the four channels for the scanline into the buffer
  40448. for (i = 0; i < 4; i++) {
  40449. endIndex = (i + 1) * scanline_width;
  40450. while (index < endIndex) {
  40451. a = uint8array[dataIndex++];
  40452. b = uint8array[dataIndex++];
  40453. if (a > 128) {
  40454. // a run of the same value
  40455. count = a - 128;
  40456. if ((count == 0) || (count > endIndex - index)) {
  40457. throw "HDR Bad Format, bad scanline data (run)";
  40458. }
  40459. while (count-- > 0) {
  40460. scanLineArray[index++] = b;
  40461. }
  40462. }
  40463. else {
  40464. // a non-run
  40465. count = a;
  40466. if ((count == 0) || (count > endIndex - index)) {
  40467. throw "HDR Bad Format, bad scanline data (non-run)";
  40468. }
  40469. scanLineArray[index++] = b;
  40470. if (--count > 0) {
  40471. for (var j = 0; j < count; j++) {
  40472. scanLineArray[index++] = uint8array[dataIndex++];
  40473. }
  40474. }
  40475. }
  40476. }
  40477. }
  40478. // now convert data from buffer into floats
  40479. for (i = 0; i < scanline_width; i++) {
  40480. a = scanLineArray[i];
  40481. b = scanLineArray[i + scanline_width];
  40482. c = scanLineArray[i + 2 * scanline_width];
  40483. d = scanLineArray[i + 3 * scanline_width];
  40484. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  40485. }
  40486. num_scanlines--;
  40487. }
  40488. return resultArray;
  40489. };
  40490. return HDRTools;
  40491. })();
  40492. Internals.HDRTools = HDRTools;
  40493. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40494. })(BABYLON || (BABYLON = {}));
  40495. var BABYLON;
  40496. (function (BABYLON) {
  40497. var HDRCubeTexture = (function (_super) {
  40498. __extends(HDRCubeTexture, _super);
  40499. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  40500. if (noMipmap === void 0) { noMipmap = false; }
  40501. if (generateHarmonics === void 0) { generateHarmonics = true; }
  40502. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  40503. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  40504. _super.call(this, scene);
  40505. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  40506. this._useInGammaSpace = false;
  40507. this._generateHarmonics = true;
  40508. this.sphericalPolynomial = null;
  40509. this.isPMREM = false;
  40510. this.name = url;
  40511. this.url = url;
  40512. this._noMipmap = noMipmap;
  40513. this.hasAlpha = false;
  40514. this._size = size;
  40515. this._useInGammaSpace = useInGammaSpace;
  40516. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  40517. this.isPMREM = this._usePMREMGenerator;
  40518. if (!url) {
  40519. return;
  40520. }
  40521. this._texture = this._getFromCache(url, noMipmap);
  40522. if (!this._texture) {
  40523. if (!scene.useDelayedTextureLoading) {
  40524. this.loadTexture();
  40525. }
  40526. else {
  40527. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40528. }
  40529. }
  40530. this.isCube = true;
  40531. this._textureMatrix = BABYLON.Matrix.Identity();
  40532. }
  40533. HDRCubeTexture.prototype.loadTexture = function () {
  40534. var _this = this;
  40535. var callback = function (buffer) {
  40536. // Extract the raw linear data.
  40537. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  40538. // Generate harmonics if needed.
  40539. if (_this._generateHarmonics) {
  40540. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  40541. }
  40542. var results = [];
  40543. var byteArray = null;
  40544. // Create uintarray fallback.
  40545. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  40546. // 3 channels of 1 bytes per pixel in bytes.
  40547. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  40548. byteArray = new Uint8Array(byteBuffer);
  40549. }
  40550. // Push each faces.
  40551. for (var j = 0; j < 6; j++) {
  40552. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  40553. // If special cases.
  40554. if (_this._useInGammaSpace || byteArray) {
  40555. for (var i = 0; i < _this._size * _this._size; i++) {
  40556. // Put in gamma space if requested.
  40557. if (_this._useInGammaSpace) {
  40558. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  40559. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  40560. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  40561. }
  40562. // Convert to int texture for fallback.
  40563. if (byteArray) {
  40564. // R
  40565. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  40566. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  40567. // G
  40568. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  40569. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  40570. // B
  40571. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  40572. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  40573. }
  40574. }
  40575. }
  40576. results.push(dataFace);
  40577. }
  40578. return results;
  40579. };
  40580. var mipmapGenerator = null;
  40581. if (!this._noMipmap && this._usePMREMGenerator) {
  40582. mipmapGenerator = function (data) {
  40583. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  40584. return generator.filterCubeMap();
  40585. };
  40586. }
  40587. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  40588. };
  40589. HDRCubeTexture.prototype.clone = function () {
  40590. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  40591. // Base texture
  40592. newTexture.level = this.level;
  40593. newTexture.wrapU = this.wrapU;
  40594. newTexture.wrapV = this.wrapV;
  40595. newTexture.coordinatesIndex = this.coordinatesIndex;
  40596. newTexture.coordinatesMode = this.coordinatesMode;
  40597. return newTexture;
  40598. };
  40599. // Methods
  40600. HDRCubeTexture.prototype.delayLoad = function () {
  40601. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40602. return;
  40603. }
  40604. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40605. this._texture = this._getFromCache(this.url, this._noMipmap);
  40606. if (!this._texture) {
  40607. this.loadTexture();
  40608. }
  40609. };
  40610. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  40611. return this._textureMatrix;
  40612. };
  40613. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40614. var texture = null;
  40615. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40616. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  40617. texture.name = parsedTexture.name;
  40618. texture.hasAlpha = parsedTexture.hasAlpha;
  40619. texture.level = parsedTexture.level;
  40620. texture.coordinatesMode = parsedTexture.coordinatesMode;
  40621. }
  40622. return texture;
  40623. };
  40624. HDRCubeTexture.prototype.serialize = function () {
  40625. if (!this.name) {
  40626. return null;
  40627. }
  40628. var serializationObject = {};
  40629. serializationObject.name = this.name;
  40630. serializationObject.hasAlpha = this.hasAlpha;
  40631. serializationObject.isCube = true;
  40632. serializationObject.level = this.level;
  40633. serializationObject.size = this._size;
  40634. serializationObject.coordinatesMode = this.coordinatesMode;
  40635. serializationObject.useInGammaSpace = this._useInGammaSpace;
  40636. serializationObject.generateHarmonics = this._generateHarmonics;
  40637. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  40638. return serializationObject;
  40639. };
  40640. HDRCubeTexture._facesMapping = [
  40641. "right",
  40642. "up",
  40643. "front",
  40644. "left",
  40645. "down",
  40646. "back"
  40647. ];
  40648. return HDRCubeTexture;
  40649. })(BABYLON.BaseTexture);
  40650. BABYLON.HDRCubeTexture = HDRCubeTexture;
  40651. })(BABYLON || (BABYLON = {}));
  40652. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;void main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}","blackAndWhitePixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;void main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));gl_FragColor=vec4(luminance,luminance,luminance,1.0);}","blurPixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;\nuniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;void main(void)\n{\nfloat weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];texelOffset+=texelStep;}\ngl_FragColor=baseColor;}","chromaticAberrationPixelShader":"precision highp float;\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;uniform float screen_width;uniform float screen_height;\nvarying vec2 vUV;void main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);float radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec4 original=texture2D(textureSampler,vUV);if (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*radius*17.0/screen_width;float ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);original.r=texture2D(textureSampler,ref_coords_r).r;original.g=texture2D(textureSampler,ref_coords_g).g;original.b=texture2D(textureSampler,ref_coords_b).b;}\ngl_FragColor=original;}","colorPixelShader":"precision highp float;uniform vec4 color;void main(void) {\ngl_FragColor=color;}","colorVertexShader":"precision highp float;\nattribute vec3 position;\nuniform mat4 worldViewProjection;void main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);}","colorCorrectionPixelShader":"precision highp float;\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\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);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(texture,vec2(s0,uv.y));vec4 slice1Color=texture2D(texture,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}","convolutionPixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];void main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 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];float kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];if (kernelWeight<=0.0) {\nkernelWeight=1.0;}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;uniform vec3 vAmbientColor;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\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;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;uniform sampler2D ambientSampler;uniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;uniform sampler2D opacitySampler;uniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;uniform vec2 vEmissiveInfos;uniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;uniform vec2 vLightmapInfos;uniform 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;uniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;uniform vec2 vSpecularInfos;uniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform 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;uniform 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);\nvec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\nfloat alpha=vDiffuseColor.a;\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;vec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);specularColor=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.);lightingInfo 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;if (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=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;reflectionColor=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);refractionColor*=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);alpha*=(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);alpha+=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);emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);diffuseBase*=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;}","defaultVertexShader":"precision highp float;\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;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;uniform vec2 vSpecularInfos;uniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;uniform vec3 vBumpInfos;uniform 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);vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=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));}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));}\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":"precision highp float;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\nuniform float far;void 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;gl_FragColor=vec4(depth,depth*depth,0.0,1.0);}","depthVertexShader":"precision highp float;\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform 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":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;\nuniform vec2 screenSize;void main(void)\n{\nvec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}","depthOfFieldPixelShader":"\n\n\n\nprecision highp float;\nuniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;\nuniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;\nuniform float screen_distance; \nuniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;\nuniform float near;uniform float far;\nvarying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);if (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);}\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\nreturn col;}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_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));\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;if (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\nfloat blur_amount=max(edge_blur_amount,coc);\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}\n}\n","displayPassPixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler;void main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);}","filterPixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;void main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}","fxaaPixelShader":"precision highp float;\n#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;uniform sampler2D textureSampler;uniform vec2 texelSize;void main(){\nvec2 localTexelSize=texelSize;vec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));vec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));vec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));vec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));vec4 rgbM=texture2D(textureSampler,vUV);vec4 luma=vec4(0.299,0.587,0.114,1.0);float lumaNW=dot(rgbNW,luma);float lumaNE=dot(rgbNE,luma);float lumaSW=dot(rgbSW,luma);float lumaSE=dot(rgbSE,luma);float lumaM=dot(rgbM,luma);float lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));float lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));vec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));float dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);float rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);dir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;vec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));vec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));float lumaB=dot(rgbB,luma);if ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;}\nelse {\ngl_FragColor=rgbB;}\n}","hdrPixelShader":"precision highp float;uniform sampler2D textureSampler;varying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];uniform float blurWeights[9];uniform float multiplier;void main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);for (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;gl_FragColor=color;}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;void main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);sum.a=clamp(sum.a,0.0,1.0);gl_FragColor=sum;}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];void main() {\nfloat average=0.0;vec4 color=vec4(0.0,0.0,0.0,0.0);float maximum=-1e20;for (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);float GreyValue=length(color.rgb);maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}\naverage=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];uniform 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);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(value*bit_shift);res-=res.xxyz*bit_mask;return res;}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);float average=0.0;for (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}\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];uniform float brightThreshold;void main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);}\ngl_FragColor=average;}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];void main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;uniform float exposure;uniform float avgLuminance;void main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);vec4 adjustedColor=color/avgLuminance*exposure;color=adjustedColor;color.a=1.0;gl_FragColor=color;}\n#endif\n","layerPixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;\nuniform vec4 color;void main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;}","layerVertexShader":"precision highp float;\nattribute vec2 position;\nuniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;\nvarying vec2 vUV;const vec2 madd=vec2(0.5,0.5);void main(void) { \nvec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);}","legacydefaultPixelShader":"precision highp float;\n#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;uniform vec3 vAmbientColor;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\nvarying vec3 vPositionW;varying 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;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;uniform sampler2D ambientSampler;uniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;uniform sampler2D opacitySampler;uniform 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;uniform vec2 vEmissiveInfos;uniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;uniform vec2 vSpecularInfos;uniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\nvec4 baseColor=vec4(1.,1.,1.,1.);vec3 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);\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.);lightingInfo info;float glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);glossiness=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;reflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);reflectionColor*=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);alpha*=(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);alpha+=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);emissiveColor*=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);diffuseBase*=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;}","legacydefaultVertexShader":"precision highp float;\nattribute vec3 position;attribute 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;uniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;uniform vec2 vSpecularInfos;uniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;uniform vec2 vBumpInfos;uniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;varying 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;varying vec3 vReflectionUVW;uniform mat4 reflectionMatrix;vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));return vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;vec3 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);vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\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));}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));}\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));}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;\nuniform vec4 color;void main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;}","lensFlareVertexShader":"precision highp float;\nattribute vec2 position;\nuniform mat4 viewportMatrix;\nvarying vec2 vUV;const vec2 madd=vec2(0.5,0.5);void main(void) { \nvUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);}","lensHighlightsPixelShader":"precision highp float;\nuniform sampler2D textureSampler; \n\nuniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;\nvarying vec2 vUV;\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (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);highlight*=luminance*gain;highlight.a=1.0;return highlight;}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}\nfloat w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;\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)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=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)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;gl_FragColor=blurred;\n}","linePixelShader":"precision highp float;uniform vec4 color;void main(void) {\ngl_FragColor=color;}","lineVertexShader":"precision highp float;\nattribute vec3 position;attribute vec4 normal;\nuniform mat4 worldViewProjection;uniform float width;uniform float aspectRatio;void main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;}","outlinePixelShader":"precision highp float;uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;}","outlineVertexShader":"precision highp float;\nattribute vec3 position;attribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform 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":"precision highp float;\nvarying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform 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);gl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;}","particlesVertexShader":"precision highp float;\nattribute vec3 position;attribute vec4 color;attribute vec4 options;\nuniform mat4 view;uniform mat4 projection;\nvarying vec2 vUV;varying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;uniform mat4 invView;varying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;float size=options.y;float angle=options.x;vec2 offset=options.zw;cornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;\nviewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); \nvColor=color;vUV=offset;\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);fClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;void main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);}","postprocessVertexShader":"precision highp float;\nattribute vec2 position;\nvarying vec2 vUV;const vec2 madd=vec2(0.5,0.5);void main(void) { \nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);}","proceduralVertexShader":"precision highp float;\nattribute vec2 position;\nvarying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);void main(void) { \nvPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);}","refractionPixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;\nuniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}","shadowMapPixelShader":"precision highp float;vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);vec2 color=vec2(depth,fract(depth*255.));return color-(color.yy*bitOffset);}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;uniform 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;float depth=length(directionToLight);depth=(depth-depthValues.x)/(depthValues.y-depthValues.x);depth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;depth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;float moment2=moment1*moment1;gl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"precision highp float;\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform 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);gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);gl_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":"precision highp float;uniform bool alphaTest;varying vec4 vColor;\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);if (alphaTest) \n{\nif (color.a<0.95)\ndiscard;}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;}","spritesVertexShader":"precision highp float;\nattribute vec4 position;attribute vec4 options;attribute vec4 cellInfo;attribute vec4 color;\nuniform vec2 textureInfos;uniform mat4 view;uniform mat4 projection;\nvarying vec2 vUV;varying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=options.zw;vec2 uvScale=textureInfos.xy;cornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;\nviewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));vUV=(uvOffset+cellInfo.zw)*uvScale;\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"precision highp float;uniform sampler2D textureSampler;uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;varying vec2 vUV;vec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);hemiRay=position+sign(dot(ray,normal))*ray;occlusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;difference=depth-occlusionDepth;occlusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor.r=result;gl_FragColor.g=result;gl_FragColor.b=result;gl_FragColor.a=1.0;}\n","ssaoCombinePixelShader":"precision highp float;uniform sampler2D textureSampler;uniform sampler2D originalColor;varying vec2 vUV;void main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);vec4 sceneColor=texture2D(originalColor,vUV);gl_FragColor=sceneColor*ssaoColor;}\n","stereoscopicInterlacePixelShader":"precision highp float;const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;void main(void)\n{\nbool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);}","tonemapPixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=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);}","volumetricLightScatteringPixelShader":"precision highp float;uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;void main(void) {\nvec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;vec4 sample=texture2D(lightScatteringSampler,tc)*0.4;sample*=illuminationDecay*weight;color+=sample;illuminationDecay*=decay;}\nvec4 realColor=texture2D(textureSampler,vUV);gl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));}\n","volumetricLightScatteringPassPixelShader":"precision highp float;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n#if defined(DIFFUSE_COLOR_RENDER)\nuniform vec3 color;\n#endif\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;uniform float opacityLevel;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\n#endif\n#ifdef ALPHATEST\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\n#ifdef OPACITY\nvec4 opacityColor=texture2D(opacitySampler,vUV);float alpha=1.0;\n#ifdef OPACITYRGB\nopacityColor.rgb=opacityColor.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityColor.x+opacityColor.y+opacityColor.z)*opacityLevel;\n#else\nalpha*=opacityColor.a*opacityLevel;\n#endif\n#if defined(BASIC_RENDER)\ngl_FragColor=vec4(diffuseColor.rgb,alpha);\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,alpha);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,alpha);\n#endif\ngl_FragColor.a=alpha;\n#else\n#if defined(BASIC_RENDER)\ngl_FragColor=diffuseColor;\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,1.0);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n#endif\n#endif\n}\n","vrDistortionCorrectionPixelShader":"precision highp float;\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);if (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);else{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);}\n}"};
  40653. 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?!1:!0},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)?!0:!1},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;var i=function(){function i(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 i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.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},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.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},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.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},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.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},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.prototype.toLinearSpace=function(){var t=new i;return this.toLinearSpaceToRef(t),t},i.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},i.prototype.toGammaSpace=function(){var t=new i;return this.toGammaSpaceToRef(t),t},i.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},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||7!==n.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16);return i.FromInts(r,o,s)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2])},i.FromInts=function(t,n,r){return new i(t/255,n/255,r/255)},i.Lerp=function(t,n,r){var o=t.r+(n.r-t.r)*r,s=t.g+(n.g-t.g)*r,e=t.b+(n.b-t.b)*r;return new i(o,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var n=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.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},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.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},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.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},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.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},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.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},i}();t.Color4=n;var r=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,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,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c;return new i(y,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=r;var o=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.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},i.prototype.toQuaternion=function(){var t=new e(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),h=Math.sin(.5*this.y);return t.x=r*h,t.y=-o*h,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.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},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.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},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.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},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.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},i.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},i.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},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.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},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.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},i.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},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.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]},i.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]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,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,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c,f=t.z*a+r.z*u+n.z*m+o.z*c;return new i(y,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.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},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,a=o.x,u=o.y,m=h.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,a+s/2,e/2+u,0,1),c=n.multiply(r).multiply(m);return i.TransformCoordinates(t,c)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),c=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(c,1)&&(m=m.scale(1/c)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.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},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e=n.normalize(),h=o.normalize(),a=y.X,u=y.Y,m=0,c=0,p=0,f=0,l=0,x=0,z=0,w=-1,v=0,d=M.Vector3[0],g=0,T=M.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?f=1:(z=h.z/h.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=f,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,d),d.normalize(),i.Dot(h,d)<0&&(w=1),g=i.Dot(e,T),g=Math.min(1,Math.max(-1,g)),p=Math.acos(g)*w,i.Dot(T,a)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),v++);var R=M.Vector3[2],_=M.Vector3[3];f=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?f=1:(z=T.z/T.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=f,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,d),d.normalize(),i.Dot(T,d)<0&&(w=1),g=i.Dot(h,R),g=Math.min(1,Math.max(-1,g)),c=Math.acos(g)*w,i.Dot(_,u)<0&&(c=Math.PI+c,v++),w=-1,i.CrossToRef(a,T,d),d.normalize(),i.Dot(d,u)<0&&(w=1),g=i.Dot(T,a),g=Math.min(1,Math.max(-1,g)),m=-Math.acos(g)*w,0>g&&2>v&&(m=Math.PI+m),s.x=c,s.y=m,s.z=p},i}();t.Vector3=o;var s=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.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},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.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},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.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},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.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},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.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},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.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},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.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},i.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},i.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},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.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},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.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},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=s;var e=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=o.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,c=e*e,y=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*c-2*y),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*y)}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],c=r[6],y=r[10],p=o+a+y;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(c-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>y?(n=2*Math.sqrt(1+o-a-y),i.w=(c-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>y?(n=2*Math.sqrt(1+a-o-y),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+c)/n):(n=2*Math.sqrt(1+y-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+c)/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),c=Math.sin(e),y=Math.cos(e);r.x=y*u*a+c*m*h,r.y=c*m*a-y*u*h,r.z=y*m*h-c*u*a,r.w=y*m*a+c*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=e;var h=function(){function i(){this.m=new Float32Array(16)}return i.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]?!1:!0},i.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)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.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],c=this.m[10],y=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=c*x-y*l,w=m*x-y*f,v=m*l-c*f,d=u*x-y*p,g=u*l-c*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,I=s*f-e*p,S=h*y-a*c,E=e*y-a*m,q=e*c-h*m,D=s*y-a*u,V=s*c-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*I)*b,t.m[14]=-(i*P-n*C+r*I)*b,t.m[3]=-(n*S-r*E+o*q)*b,t.m[7]=(i*S-r*D+o*V)*b,t.m[11]=-(i*E-n*D+o*W)*b,t.m[15]=(i*q-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.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},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.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],c=this.m[8],y=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],I=t.m[14],S=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*I,i[n+3]=r*T+o*F+s*P+e*S,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*I,i[n+7]=h*T+a*F+u*P+m*S,i[n+8]=c*v+y*R+p*b+f*Z,i[n+9]=c*d+y*_+p*A+f*C,i[n+10]=c*g+y*M+p*L+f*I,i[n+11]=c*T+y*F+p*P+f*S,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*I,i[n+15]=l*T+x*F+z*P+w*S,this},i.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]},i.prototype.clone=function(){return i.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])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,h=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=t.Tools.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=h*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=i.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 e.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,c,y,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]=c,x.m[12]=y,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){var z=new i;return z.m[0]=t,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]=c,z.m[11]=y,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.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},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.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,\ni.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},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.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},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.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},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){e.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.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},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var s=new o(0,0,0),h=new e,a=new o(0,0,0);t.decompose(s,h,a);var u=new o(0,0,0),m=new e,c=new o(0,0,0);n.decompose(u,m,c);var y=o.Lerp(s,u,r),p=e.Slerp(h,m,r),f=o.Lerp(a,c,r);return i.Compose(y,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,s){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-o.Dot(this._xAxis,t),h=-o.Dot(this._yAxis,t),a=-o.Dot(this._zAxis,t);return i.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,s)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.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},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,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},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,c=i.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(c)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.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]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.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},i._tempQuaternion=new e,i._xAxis=o.Zero(),i._yAxis=o.Zero(),i._zAxis=o.Zero(),i}();t.Matrix=h;var a=function(){function t(t,i,n,r){this.normal=new o(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=h.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,a=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],c=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(a,u,m,c)},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,c=e*h-o*u,y=o*a-s*h,p=Math.sqrt(m*m+c*c+y*y);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=c*r,this.normal.z=y*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=o.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return o.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 o.Dot(n,i)+r},t}();t.Plane=a;var u=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){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new a(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=m;var c=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=o.Zero(),this._edge2=o.Zero(),this._pvec=o.Zero(),this._tvec=o.Zero(),this._qvec=o.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),o.CrossToRef(this.direction,this._edge2,this._pvec);var s=o.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var h=o.Dot(this._tvec,this._pvec)*e;if(0>h||h>1)return null;o.CrossToRef(this._tvec,this._edge1,this._qvec);var a=o.Dot(this.direction,this._qvec)*e;if(0>a||h+a>1)return null;var u=o.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,s,e,h,a){var u=o.Unproject(new o(t,n,0),r,s,e,h,a),m=o.Unproject(new o(t,n,1),r,s,e,h,a),c=m.subtract(u);return c.normalize(),new i(u,c)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=h.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=o.TransformCoordinates(t.origin,n),s=o.TransformNormal(t.direction,n);return new i(r,s,t.length)},i}();t.Ray=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var y=(t.Space,function(){function t(){}return t.X=new o(1,0,0),t.Y=new o(0,1,0),t.Z=new o(0,0,1),t}());t.Axis=y;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,c=m*a,y=s*c+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(y-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 o=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-o)/2,e=(o-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 r((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){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new o(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var w=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var o=new r(i,n),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},i.prototype.addArcTo=function(i,n,o,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new r(i,n),u=new r(o,s),m=new x(h,a,u),c=m.angle.radians()/e;m.orientation===f.CW&&(c*=-1);for(var y=m.startAngle.radians()+c,p=0;e>p;p++){var l=Math.cos(y)*m.radius+m.centerPoint.x,z=Math.sin(y)*m.radius+m.centerPoint.y;this.addLineTo(l,z),y+=c}return this},i.prototype.close=function(){return this.closed=!0,this},i.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},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),r.Zero();for(var n=i*this.length(),o=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,h=this._points[s],a=this._points[e],u=a.subtract(h),m=u.length()+o;if(n>=o&&m>=n){var c=u.normalize(),y=n-o;return new r(h.x+c.x*y,h.y+c.y*y)}o=m}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=w;var v=function(){function i(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 i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.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},i.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]=o.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,h,a,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=o.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=o.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.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},i.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},i.prototype._normalVector=function(i,n,r){var s;if(void 0===r||null===r){var e;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(e=new o(0,0,1)):e=new o(1,0,0):e=new o(0,-1,0),s=o.Cross(n,e)}else s=o.Cross(n,r),o.CrossToRef(s,n,s);return s.normalize(),s},i}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,s){s=s>2?s: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;s>=a;a++)e.push(new o(h(a/s,i.x,n.x,r.x),h(a/s,i.y,n.y,r.y),h(a/s,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,s,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 o(a(u/e,i.x,n.x,r.x,s.x),a(u/e,i.y,n.y,r.y,s.y),a(u/e,i.z,n.z,r.z,s.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,s,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(o.Hermite(i,n,r,s,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=d;var g=function(){function t(){this.L00=o.Zero(),this.L1_1=o.Zero(),this.L10=o.Zero(),this.L11=o.Zero(),this.L2_2=o.Zero(),this.L2_1=o.Zero(),this.L20=o.Zero(),this.L21=o.Zero(),this.L22=o.Zero()}return t.prototype.addLight=function(t,i,n){var r=new o(i.r,i.g,i.b),s=r.scale(n);this.L00=this.L00.add(s.scale(.282095)),this.L1_1=this.L1_1.add(s.scale(.488603*t.y)),this.L10=this.L10.add(s.scale(.488603*t.z)),this.L11=this.L11.add(s.scale(.488603*t.x)),this.L2_2=this.L2_2.add(s.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(s.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(s.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(s.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(s.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=g;var T=function(){function t(){this.x=o.Zero(),this.y=o.Zero(),this.z=o.Zero(),this.xx=o.Zero(),this.yy=o.Zero(),this.zz=o.Zero(),this.xy=o.Zero(),this.yz=o.Zero(),this.zx=o.Zero()}return t.prototype.addAmbient=function(t){var i=new o(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=T;var R=function(){function t(t,i){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),void 0===n&&(n=r.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=_;var M=function(){function t(){}return t.Color3=[i.Black(),i.Black(),i.Black()],t.Vector2=[r.Zero(),r.Zero(),r.Zero()],t.Vector3=[o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new e(0,0,0,0)],t.Matrix=[h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  40654. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];attribute vec4 matricesIndices;attribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;influence=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;bumpUV+=uvOffset;\n#ifdef PARALLAXOCCLUSION\nif (diffuseUV.x>1.0 || diffuseUV.y>1.0 || diffuseUV.x<0.0 || diffuseUV.y<0.0) {\ndiscard;}\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;uniform vec3 vBumpInfos;uniform sampler2D bumpSampler;\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);\nvec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));return mat3(tangent*invmax,binormal*invmax,normal);}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;map=map*255./127.-128./127.;return normalize(cotangentFrame*map);}\n#ifdef PARALLAX\nconst float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;\nfloat currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;for (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\nbreak;}\nelse\n{\ncurrRayHeight-=stepSize;vLastOffset=vCurrOffset;vCurrOffset+=stepSize*vMaxOffset;lastSampledHeight=currSampledHeight;}\n}\nreturn vCurrOffset;}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;return -texCoordOffset;}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;}\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;varying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();color.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;uniform vec3 vFogColor;varying float fFogDistance;float CalcFogFactor()\n{\nfloat fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;if (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\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);return clamp(fresnelTerm,0.,1.);}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute 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};uniform 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};uniform 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};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));result.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));if (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));result.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;result.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;varying 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;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\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);float t=clamp(direction.y*-0.5+0.5,0.,1.0);float s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;return vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);vec3 r=reflect(cameraToVertex,worldNormal);float t=clamp(r.y*-0.5+0.5,0.,1.0);float s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;return vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r.z=r.z-1.0;float m=2.0*length(r);return 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;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;vec3 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);return dot(color,bit_shift);}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;float computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;float depth=length(directionToLight);depth=(depth-depthValues.x)/(depthValues.y-depthValues.x);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;if (depth>shadow)\n{\nreturn darkness;}\nreturn 1.0;}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;float depth=length(directionToLight);depth=(depth-depthValues.x)/(depthValues.y-depthValues.x);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);\nfloat biasedDepth=depth-bias;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;return min(1.0,visibility+darkness);}\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;depth=0.5*depth+vec3(0.5);vec2 uv=depth.xy;if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;if (depth.z>shadow)\n{\nreturn darkness;}\nreturn 1.;}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;depth=0.5*depth+vec3(0.5);vec2 uv=depth.xy;if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;}\nfloat visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);\nfloat biasedDepth=depth.z-bias;if (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;if (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;if (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;if (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;return min(1.0,visibility+darkness);}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);float variance=max(moments.y-moments.x*moments.x,0.02);float d=compare-moments.x;float p_max=linstep(0.2,1.0,variance/(variance+d*d));return clamp(max(p,p_max),0.0,1.0);}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;depth=0.5*depth+vec3(0.5);vec2 uv=depth.xy;if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;}\nvec4 texel=texture2D(shadowSampler,uv);vec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));return min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);}\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;varying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;varying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;varying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;varying vec4 vPositionFromLight3;\n#endif\n#endif"};
  40655. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  40656. module.exports = BABYLON;
  40657. };